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 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
//! A middleware for [actionable](https://github.com/actix/actix-web) that provides
//! rate-limiting backed by [governor](https://github.com/antifuchs/governor).
//!
//! # Features:
//!
//! + Simple to use
//! + High customizability
//! + High performance
//! + Robust yet flexible API
//!
//! # How does it work?
//!
//! Each governor middleware has a configuration that stores a quota.
//! The quota specifies how many requests can be sent from an IP address
//! before the middleware starts blocking further requests.
//!
//! For example if the quota allowed ten requests a client could send a burst of
//! ten requests in short time before the middleware starts blocking.
//!
//! Once at least one element of the quota was used the elements of the quota
//! will be replenished after a specified period.
//!
//! For example if this period was 2 seconds and the quota was empty
//! it would take 2 seconds to replenish one element of the quota.
//! This means you could send one request every two seconds on average.
//!
//! If there was a quota that allowed ten requests with the same period
//! a client could again send a burst of ten requests and then had to wait
//! two seconds before sending further requests or 20 seconds before the full
//! quota would be replenished and he could send another burst.
//!
//! # Example
//! ```rust,no_run
//! use actix_governor::{Governor, GovernorConfigBuilder};
//! use actix_web::{web, App, HttpServer, Responder};
//!
//! async fn index() -> impl Responder {
//! "Hello world!"
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//! // Allow bursts with up to five requests per IP address
//! // and replenishes one element every two seconds
//! let governor_conf = GovernorConfigBuilder::default()
//! .per_second(2)
//! .burst_size(5)
//! .finish()
//! .unwrap();
//!
//! HttpServer::new(move || {
//! App::new()
//! // Enable Governor middleware
//! .wrap(Governor::new(&governor_conf))
//! // Route hello world service
//! .route("/", web::get().to(index))
//! })
//! .bind("127.0.0.1:8080")?
//! .run()
//! .await
//! }
//! ```
//!
//! # Configuration presets
//!
//! Instead of using the configuration builder you can use predefined presets.
//!
//! + [`GovernorConfig::default()`]: The default configuration which is suitable for most services.
//! Allows bursts with up to eight requests and replenishes one element after 500ms, based on peer IP.
//!
//! + [`GovernorConfig::secure()`]: A default configuration for security related services.
//! Allows bursts with up to two requests and replenishes one element after four seconds, based on peer IP.
//!
//! For example the secure configuration can be used as a short version of this code:
//!
//! ```rust
//! use actix_governor::GovernorConfigBuilder;
//!
//! let config = GovernorConfigBuilder::default()
//! .per_second(4)
//! .burst_size(2)
//! .finish()
//! .unwrap();
//! ```
//!
//! # Customize rate limiting key
//!
//! By default, rate limiting is done using the peer IP address (i.e. the IP address of the HTTP client that requested your app: either your user or a reverse proxy, depending on your deployment setup).
//! You can configure a different behavior which:
//! 1. can be useful in itself
//! 2. allows you to setup multiple instances of this middleware based on different keys (for example, if you want to apply rate limiting with different rates on IP and API keys at the same time)
//!
//! This is achieved by defining a [KeyExtractor] and giving it to a [Governor] instance.
//! Two ready-to-use key extractors are provided:
//! - [PeerIpKeyExtractor]: this is the default
//! - [GlobalKeyExtractor]: uses the same key for all incoming requests
//!
//! Check out the [custom_key](https://github.com/AaronErhardt/actix-governor/blob/main/examples/custom_key.rs) example to see how a custom key extractor can be implemented.
//!
//! # Customizing error responses
//!
//! There are two errors that might occur during rate-limiting.
//! The first error occurs when the key can't be extracted from the request, for example when a session id is missing.
//! The second error occurs when the rate limit is exceeded.
//!
//! ## The response when key-extractions fails
//! The response for this error is generated by the implementation of [`ResponseError::error_response`] for [KeyExtractor::KeyExtractionError].
//! With this method you can generate any [`HttpResponse`] you want, [for example to return json].
//!
//! But it has a simplistic problem that you can't access the request directly, but you can solve it by creating a
//! `new` method in the struct and passing the request that is given to you is in a method [`KeyExtractor::extract`] to it and do whatever you want with it
//!
//! For most cases can simply use [`SimpleKeyExtractionError`] to return an error.
//! It returns a response with the body you set in `new`, type `text/plain` and `500 Internal Server Error` status by default,
//! but you can customize the content type with [`set_content_type`] and the status with [`set_status_code`].
//!
//! [`ResponseError::error_response`]: actix_web::error::ResponseError::error_response
//! [`set_status_code`]: SimpleKeyExtractionError::set_status_code
//! [`set_content_type`]: SimpleKeyExtractionError::set_content_type
//! [for example to return json]: https://github.com/AaronErhardt/actix-governor/blob/main/examples/custom_key_bearer.rs
//! [`HttpResponse`]: actix_web::HttpResponse
//!
//! ## The response of exceeding the rate limit
//! The response of this error is generated by [`KeyExtractor::exceed_rate_limit_response`].
//! This method will give you a [`HttpResponseBuilder`] and return a [`HttpResponse`].
//! This allows you to fully customize the response.
//!
//! Check out the [custom_key_bearer] example for more information.
//!
//! [`HttpResponseBuilder`]: actix_web::HttpResponseBuilder
//! [`HttpResponse`]: actix_web::HttpResponse
//! [custom_key_bearer]: https://github.com/AaronErhardt/actix-governor/blob/main/examples/custom_key_bearer.rs
//!
//! # Add x-ratelimit headers
//!
//! By default, `x-ratelimit-after` is enabled but if you want to enable `x-ratelimit-limit`, `x-ratelimit-whitelisted` and `x-ratelimit-remaining` use [`use_headers`] method
//!
//! [`use_headers`]: crate::GovernorConfigBuilder::use_headers()
//!
//! # Common pitfalls
//!
//! Do not construct the same configuration multiple times, unless explicitly wanted!
//! This will create an independent rate limiter for each configuration!
//!
//! Instead pass the same configuration reference into [`Governor::new()`],
//! like it is described in the example.
#![warn(
rust_2018_idioms,
unreachable_pub,
missing_docs,
clippy::must_use_candidate,
clippy::cargo
)]
#[cfg(test)]
mod tests;
use governor::{
clock::{DefaultClock, QuantaInstant},
middleware::{NoOpMiddleware, RateLimitingMiddleware, StateInformationMiddleware},
state::keyed::DefaultKeyedStateStore,
Quota, RateLimiter,
};
use actix_http::body::EitherBody;
use std::{cell::RefCell, marker::PhantomData, num::NonZeroU32, rc::Rc, sync::Arc, time::Duration};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::http::Method;
use actix_web::{body::MessageBody, Error};
use futures::future;
mod extractor;
mod key_extractor;
mod service;
type SharedRateLimiter<Key, M> =
Arc<RateLimiter<Key, DefaultKeyedStateStore<Key>, DefaultClock, M>>;
/// Re-export governor
pub use governor;
pub use extractor::GovernorExtractor;
pub use key_extractor::{
GlobalKeyExtractor, KeyExtractor, PeerIpKeyExtractor, SimpleKeyExtractionError,
};
const DEFAULT_PERIOD: Duration = Duration::from_millis(500);
const DEFAULT_BURST_SIZE: u32 = 8;
/// Helper struct for building a configuration for the governor middleware.
///
/// # Example
///
/// Create a configuration with a quota of ten requests per IP address
/// that replenishes one element every minute.
///
/// ```rust
/// use actix_governor::GovernorConfigBuilder;
///
/// let config = GovernorConfigBuilder::default()
/// .per_second(60)
/// .burst_size(10)
/// .finish()
/// .unwrap();
/// ```
///
/// with x-ratelimit headers
///
/// ```rust
/// use actix_governor::GovernorConfigBuilder;
///
/// let config = GovernorConfigBuilder::default()
/// .per_second(60)
/// .burst_size(10)
/// .use_headers() // Add this
/// .finish()
/// .unwrap();
/// ```
#[must_use]
#[derive(Debug, Eq)]
pub struct GovernorConfigBuilder<K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> {
period: Duration,
burst_size: u32,
methods: Option<Vec<Method>>,
key_extractor: K,
middleware: PhantomData<M>,
permissive: bool,
}
impl<K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> Clone
for GovernorConfigBuilder<K, M>
{
fn clone(&self) -> Self {
Self {
period: self.period,
burst_size: self.burst_size,
methods: self.methods.clone(),
key_extractor: self.key_extractor.clone(),
middleware: self.middleware,
permissive: self.permissive,
}
}
}
impl<K: KeyExtractor + PartialEq, M: RateLimitingMiddleware<QuantaInstant>> PartialEq
for GovernorConfigBuilder<K, M>
{
fn eq(&self, other: &Self) -> bool {
self.period == other.period
&& self.burst_size == other.burst_size
&& self.methods == other.methods
&& self.key_extractor == other.key_extractor
&& self.permissive == other.permissive
}
}
impl Default for GovernorConfigBuilder<PeerIpKeyExtractor, NoOpMiddleware> {
/// The default configuration which is suitable for most services.
/// Allows burst with up to eight requests and replenishes one element after 500ms, based on peer IP.
/// The values can be modified by calling other methods on this struct.
fn default() -> Self {
Self::const_default()
}
}
impl<M: RateLimitingMiddleware<QuantaInstant>> GovernorConfigBuilder<PeerIpKeyExtractor, M> {
/// Returns the default configuration.
pub const fn const_default() -> Self {
GovernorConfigBuilder {
period: DEFAULT_PERIOD,
burst_size: DEFAULT_BURST_SIZE,
methods: None,
key_extractor: PeerIpKeyExtractor,
middleware: PhantomData,
permissive: false,
}
}
/// Set the interval after which one element of the quota is replenished.
///
/// **The interval must not be zero.**
pub const fn const_period(mut self, duration: Duration) -> Self {
self.period = duration;
self
}
/// Set the interval after which one element of the quota is replenished in seconds.
///
/// **The interval must not be zero.**
pub const fn const_per_second(mut self, seconds: u64) -> Self {
self.period = Duration::from_secs(seconds);
self
}
/// Set the interval after which one element of the quota is replenished in milliseconds.
///
/// **The interval must not be zero.**
pub const fn const_per_millisecond(mut self, milliseconds: u64) -> Self {
self.period = Duration::from_millis(milliseconds);
self
}
/// Set the interval after which one element of the quota is replenished in nanoseconds.
///
/// **The interval must not be zero.**
pub const fn const_per_nanosecond(mut self, nanoseconds: u64) -> Self {
self.period = Duration::from_nanos(nanoseconds);
self
}
/// Set quota size that defines how many requests can occur
/// before the governor middleware starts blocking requests from an IP address and
/// clients have to wait until the elements of the quota are replenished.
///
/// **The burst_size must not be zero.**
pub const fn const_burst_size(mut self, burst_size: u32) -> Self {
self.burst_size = burst_size;
self
}
/// Set the mode of the governor middleware.
///
/// If permissive is set to true, the middleware will not block requests.
/// See also [`GovernorExtractor`](crate::GovernorExtractor).
pub const fn const_permissive(mut self, permissive: bool) -> Self {
self.permissive = permissive;
self
}
}
impl<K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> GovernorConfigBuilder<K, M> {
/// Set the interval after which one element of the quota is replenished.
///
/// **The interval must not be zero.**
pub fn period(&mut self, duration: Duration) -> &mut Self {
self.period = duration;
self
}
/// Set the interval after which one element of the quota is replenished in seconds.
///
/// **The interval must not be zero.**
pub fn per_second(&mut self, seconds: u64) -> &mut Self {
self.period = Duration::from_secs(seconds);
self
}
/// Set the interval after which one element of the quota is replenished in milliseconds.
///
/// **The interval must not be zero.**
pub fn per_millisecond(&mut self, milliseconds: u64) -> &mut Self {
self.period = Duration::from_millis(milliseconds);
self
}
/// Set the interval after which one element of the quota is replenished in nanoseconds.
///
/// **The interval must not be zero.**
pub fn per_nanosecond(&mut self, nanoseconds: u64) -> &mut Self {
self.period = Duration::from_nanos(nanoseconds);
self
}
/// Set quota size that defines how many requests can occur
/// before the governor middleware starts blocking requests from an IP address and
/// clients have to wait until the elements of the quota are replenished.
///
/// **The burst_size must not be zero.**
pub fn burst_size(&mut self, burst_size: u32) -> &mut Self {
self.burst_size = burst_size;
self
}
/// Set the mode of the governor middleware.
///
/// If permissive is set to true, the middleware will not block requests.
/// See also [`GovernorExtractor`](crate::GovernorExtractor).
pub fn permissive(&mut self, permissive: bool) -> &mut Self {
self.permissive = permissive;
self
}
/// Set the HTTP methods this configuration should apply to.
/// By default this is all methods.
pub fn methods(&mut self, methods: Vec<Method>) -> &mut Self {
self.methods = Some(methods);
self
}
/// Set the key extractor this configuration should use.
/// By default this is using the [PeerIpKeyExtractor].
pub fn key_extractor<K2: KeyExtractor>(
&mut self,
key_extractor: K2,
) -> GovernorConfigBuilder<K2, M> {
GovernorConfigBuilder {
period: self.period,
burst_size: self.burst_size,
methods: self.methods.to_owned(),
key_extractor,
middleware: PhantomData,
permissive: self.permissive,
}
}
/// Set x-ratelimit headers to response, the headers is
/// - `x-ratelimit-limit` - Request limit
/// - `x-ratelimit-remaining` - The number of requests left for the time window
/// - `x-ratelimit-after` - Number of seconds in which the API will become available after its rate limit has been exceeded
/// - `x-ratelimit-whitelisted` - If the request method not in methods, this header will be add it, use [`methods`] to add methods
///
/// By default `x-ratelimit-after` is enabled, with [`use_headers`] will enable `x-ratelimit-limit`, `x-ratelimit-whitelisted` and `x-ratelimit-remaining`
///
/// [`methods`]: crate::GovernorConfigBuilder::methods()
/// [`use_headers`]: Self::use_headers
pub fn use_headers(&mut self) -> GovernorConfigBuilder<K, StateInformationMiddleware> {
GovernorConfigBuilder {
period: self.period,
burst_size: self.burst_size,
methods: self.methods.to_owned(),
key_extractor: self.key_extractor.clone(),
middleware: PhantomData,
permissive: self.permissive,
}
}
/// Finish building the configuration and return the configuration for the middleware.
/// Returns `None` if either burst size or period interval are zero.
pub fn finish(&mut self) -> Option<GovernorConfig<K, M>> {
if self.burst_size != 0 && self.period.as_nanos() != 0 {
Some(GovernorConfig {
key_extractor: self.key_extractor.clone(),
limiter: Arc::new(
RateLimiter::keyed(
Quota::with_period(self.period)
.unwrap()
.allow_burst(NonZeroU32::new(self.burst_size).unwrap()),
)
.with_middleware::<M>(),
),
methods: self.methods.clone(),
permissive: self.permissive,
})
} else {
None
}
}
}
#[derive(Debug)]
#[must_use]
/// Configuration for the Governor middleware.
pub struct GovernorConfig<K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> {
key_extractor: K,
limiter: SharedRateLimiter<K::Key, M>,
methods: Option<Vec<Method>>,
permissive: bool,
}
impl<K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> Clone for GovernorConfig<K, M> {
fn clone(&self) -> Self {
GovernorConfig {
key_extractor: self.key_extractor.clone(),
limiter: self.limiter.clone(),
methods: self.methods.clone(),
permissive: self.permissive,
}
}
}
impl Default for GovernorConfig<PeerIpKeyExtractor, NoOpMiddleware> {
/// The default configuration which is suitable for most services.
/// Allows bursts with up to eight requests and replenishes one element after 500ms, based on peer IP.
fn default() -> Self {
GovernorConfigBuilder::default().finish().unwrap()
}
}
impl<M: RateLimitingMiddleware<QuantaInstant>> GovernorConfig<PeerIpKeyExtractor, M> {
/// A default configuration for security related services.
/// Allows bursts with up to two requests and replenishes one element after four seconds, based on peer IP.
///
/// This prevents brute-forcing passwords or security tokens
/// yet allows to quickly retype a wrong password once before the quota is exceeded.
pub fn secure() -> Self {
GovernorConfigBuilder {
period: Duration::from_secs(4),
burst_size: 2,
methods: None,
key_extractor: PeerIpKeyExtractor,
middleware: PhantomData,
permissive: false,
}
.finish()
.unwrap()
}
}
/// Governor middleware factory.
pub struct Governor<K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> {
key_extractor: K,
limiter: SharedRateLimiter<K::Key, M>,
methods: Option<Vec<Method>>,
permissive: bool,
}
impl<K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> Governor<K, M> {
/// Create new governor middleware factory from configuration.
pub fn new(config: &GovernorConfig<K, M>) -> Self {
Governor {
key_extractor: config.key_extractor.clone(),
limiter: config.limiter.clone(),
methods: config.methods.clone(),
permissive: config.permissive,
}
}
}
impl<S, B, K> Transform<S, ServiceRequest> for Governor<K, NoOpMiddleware>
where
K: KeyExtractor,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
B: MessageBody,
{
type Response = ServiceResponse<EitherBody<B>>;
type Error = Error;
type Transform = GovernorMiddleware<S, K, NoOpMiddleware>;
type InitError = ();
type Future = future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
future::ok(GovernorMiddleware::<S, K, NoOpMiddleware> {
service: Rc::new(RefCell::new(service)),
key_extractor: self.key_extractor.clone(),
limiter: self.limiter.clone(),
methods: self.methods.clone(),
permissive: self.permissive,
})
}
}
impl<S, B, K> Transform<S, ServiceRequest> for Governor<K, StateInformationMiddleware>
where
K: KeyExtractor,
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
B: MessageBody,
<S as Service<ServiceRequest>>::Future: Unpin,
{
type Response = ServiceResponse<EitherBody<B>>;
type Error = Error;
type Transform = GovernorMiddleware<S, K, StateInformationMiddleware>;
type InitError = ();
type Future = future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
future::ok(GovernorMiddleware::<S, K, StateInformationMiddleware> {
service: Rc::new(RefCell::new(service)),
key_extractor: self.key_extractor.clone(),
limiter: self.limiter.clone(),
methods: self.methods.clone(),
permissive: self.permissive,
})
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// The result of a [`GovernorExtractor`].
pub enum GovernorResult<E> {
/// The request does not exceed the rate limit.
Ok {
/// The maximum burst size.
burst_size: Option<u32>,
/// The remaining burst capacity.
remaining: Option<u32>,
},
/// The request method was whitelisted.
Whitelisted,
/// The request exceeds the rate limit.
Wait {
/// The maximum burst size.
burst_size: Option<u32>,
/// The time to wait for new requests in seconds.
wait: u64,
},
/// Internal error.
Err(E),
}
impl<E> GovernorResult<E> {
const fn whitelist() -> Self {
Self::Whitelisted
}
const fn ok() -> Self {
Self::Ok {
burst_size: None,
remaining: None,
}
}
const fn ok_with_info(burst_size: u32, remaining: u32) -> Self {
Self::Ok {
burst_size: Some(burst_size),
remaining: Some(remaining),
}
}
const fn wait(wait: u64) -> Self {
Self::Wait {
wait,
burst_size: None,
}
}
const fn wait_with_info(wait: u64, burst_size: u32) -> Self {
Self::Wait {
wait,
burst_size: Some(burst_size),
}
}
const fn err(e: E) -> Self {
Self::Err(e)
}
}
impl<E> GovernorResult<E> {
/// Check if this request is rate limited.
///
/// Returns `Ok(Some(wait))` if the request is rate limited and should be retried after `wait` milliseconds.
///
/// Returns `Ok(None)` if the request is not rate limited.
///
/// # Errors
/// Returns error if key extraction failed.
pub const fn check(&self) -> Result<Option<u64>, &E> {
match self {
Self::Wait { wait, .. } => Ok(Some(*wait)),
Self::Err(e) => Err(e),
_ => Ok(None),
}
}
}
/// A middleware that implements rate limiting based on the governor crate.
pub struct GovernorMiddleware<S, K: KeyExtractor, M: RateLimitingMiddleware<QuantaInstant>> {
service: std::rc::Rc<std::cell::RefCell<S>>,
key_extractor: K,
limiter: SharedRateLimiter<K::Key, M>,
methods: Option<Vec<Method>>,
permissive: bool,
}