Skip to main content

actix_trypema/
error.rs

1//! Configuration, key-extraction, and backend-failure types.
2
3use std::{fmt, sync::Arc, time::Duration};
4
5use actix_web::{HttpResponse, ResponseError, http::StatusCode};
6use trypema::{TrypemaError, local::LocalRateLimiterProvider};
7
8/// An invalid middleware configuration, reported by `build()` and validated constructors.
9#[derive(Debug, thiserror::Error, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum ConfigError {
12    /// No namespace was configured.
13    #[error("missing namespace: call namespace(..) before build()")]
14    MissingNamespace,
15
16    /// The namespace does not match `[a-z0-9-]{1,32}`.
17    #[error("invalid namespace: {0}")]
18    InvalidNamespace(String),
19
20    /// No key extractor was configured.
21    #[error("missing key extractor: call extractor(..) before build()")]
22    MissingExtractor,
23
24    /// No rate was configured.
25    #[error("missing rate: call rate(..) or rate_fn(..) before build()")]
26    MissingRate,
27
28    /// A trusted-proxy entry is invalid.
29    #[error("invalid trusted proxy: {0}")]
30    InvalidTrustedProxy(String),
31
32    /// A header name is invalid.
33    #[error("invalid header name: {0}")]
34    InvalidHeaderName(String),
35
36    /// An IPv6 prefix length is outside `1..=128`.
37    #[error("invalid ipv6 prefix length {0}: must be between 1 and 128")]
38    InvalidIpv6PrefixLen(u8),
39
40    /// A `BackendErrorPolicy::Fallback` backend uses a different window than the primary.
41    #[error("fallback backend window must match the primary backend window")]
42    FallbackWindowMismatch,
43
44    /// A fixed rate admits less than one request per window, so every request would be
45    /// rejected.
46    #[error("rate admits less than one request per window: raise the rate or widen the window")]
47    ZeroCapacity,
48
49    /// The backend timeout is zero, so every backend call would fail.
50    #[error("backend timeout must be greater than zero")]
51    ZeroBackendTimeout,
52}
53
54/// A key-extraction failure, handled according to [`KeyErrorPolicy`].
55///
56/// With the default policy the error renders as `400 Bad Request` through
57/// [`ResponseError`]; the response body never echoes request contents.
58#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum KeyError {
61    /// The request has no peer address (for example a test request without one).
62    #[error("request has no peer address")]
63    MissingPeerAddr,
64
65    /// The configured key header is absent from the request.
66    #[error("missing key header: {name}")]
67    MissingHeader {
68        /// The configured header name.
69        name: Box<str>,
70    },
71
72    /// A trusted forwarding chain contained a malformed hop or exceeded the hop cap.
73    #[error("malformed forwarding chain")]
74    MalformedForwardedChain,
75
76    /// A key value was unusable (wrong charset or over the length cap).
77    #[error("invalid key value: {reason}")]
78    InvalidValue {
79        /// Why the value was rejected.
80        reason: &'static str,
81    },
82}
83
84impl ResponseError for KeyError {
85    fn status_code(&self) -> StatusCode {
86        StatusCode::BAD_REQUEST
87    }
88
89    fn error_response(&self) -> HttpResponse {
90        HttpResponse::build(self.status_code())
91            .content_type("text/plain; charset=utf-8")
92            .body("invalid rate limiting key")
93    }
94} // end impl
95
96/// What to do when key extraction fails.
97#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
98#[non_exhaustive]
99pub enum KeyErrorPolicy {
100    /// Reject the request, rendering the [`KeyError`] through [`ResponseError`]. The default.
101    #[default]
102    Reject,
103    /// Skip the limiter and forward the request.
104    Bypass,
105    /// Fall back to the namespace-wide shared key, as if [`Global`](crate::extract::Global)
106    /// were the extractor.
107    UseGlobalKey,
108}
109
110/// Why a Redis or hybrid backend call failed.
111#[derive(Debug, thiserror::Error)]
112#[non_exhaustive]
113pub enum BackendFailure {
114    /// The call exceeded the configured `backend_timeout`.
115    #[error("backend call timed out after {0:?}")]
116    Timeout(Duration),
117
118    /// trypema reported an error, such as an unreachable Redis.
119    #[error(transparent)]
120    Error(TrypemaError),
121}
122
123/// What to do when a Redis or hybrid backend call fails or times out.
124///
125/// The default is [`FailOpen`](Self::FailOpen): a rate limiter outage should not become an API
126/// outage. Security-sensitive routes such as login or OTP verification should use
127/// [`FailClosed`](Self::FailClosed).
128#[derive(Clone, Default)]
129#[non_exhaustive]
130pub enum BackendErrorPolicy {
131    /// Admit the request. The default.
132    #[default]
133    FailOpen,
134    /// Reject the request with `503 Service Unavailable`.
135    FailClosed,
136    /// Run the same admission check on a local provider, with the same derived key, rate, cost,
137    /// and strategy. Each app instance then enforces its own quota while the backend is
138    /// unavailable, so `n` instances admit up to `n` times the limit, and those counts are not
139    /// carried back. The provider must use the primary's window. A provider holds both
140    /// strategies, so it serves an absolute and a suppressed primary. Recorded outcomes report
141    /// the local decision (`Admitted`, `Limited`), not `BackendError`.
142    Fallback(Arc<LocalRateLimiterProvider>),
143    /// Decide per failure.
144    Custom(Arc<dyn Fn(&BackendFailure) -> ErrorAction + Send + Sync>),
145}
146
147impl fmt::Debug for BackendErrorPolicy {
148    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149        match self {
150            Self::FailOpen => formatter.write_str("FailOpen"),
151            Self::FailClosed => formatter.write_str("FailClosed"),
152            Self::Fallback(_) => formatter.write_str("Fallback(..)"),
153            Self::Custom(_) => formatter.write_str("Custom(..)"),
154        }
155    }
156} // end impl
157
158/// The decision a [`BackendErrorPolicy::Custom`] function returns.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160#[non_exhaustive]
161pub enum ErrorAction {
162    /// Admit the request.
163    Admit,
164    /// Reject the request with the given status.
165    Reject {
166        /// The response status to use.
167        status: StatusCode,
168    },
169}