Skip to main content

hyperlane_plugin_security/
impl.rs

1use super::*;
2
3/// Inherent implementation of [`SecurityViolation`].
4impl SecurityViolation {
5    /// Maps this violation to its canonical HTTP status code.
6    ///
7    /// # Returns
8    ///
9    /// - `usize` - HTTP status code (`400`, `403`, `413`, `414`, or custom).
10    pub fn status_code(&self) -> usize {
11        match self {
12            Self::BodyTooLarge => HttpStatus::PayloadTooLarge.code(),
13            Self::UriTooLong => HttpStatus::URITooLong.code(),
14            Self::InvalidHost | Self::PathTraversal => HttpStatus::BadRequest.code(),
15            Self::CsrfInvalid => HttpStatus::Forbidden.code(),
16            Self::Custom { status_code, .. } => *status_code,
17        }
18    }
19}
20
21/// Formatting for [`SecurityViolation`].
22impl Display for SecurityViolation {
23    /// Formats a human-readable description of the [`SecurityViolation`].
24    ///
25    /// # Arguments
26    ///
27    /// - `&mut Formatter<'_>` - Output formatter.
28    ///
29    /// # Returns
30    ///
31    /// - `fmt::Result` - Formatting outcome.
32    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
33        match self {
34            Self::BodyTooLarge => f.write_str(MSG_BODY_TOO_LARGE),
35            Self::UriTooLong => f.write_str(MSG_URI_TOO_LONG),
36            Self::InvalidHost => f.write_str(MSG_INVALID_HOST),
37            Self::PathTraversal => f.write_str(MSG_PATH_TRAVERSAL),
38            Self::CsrfInvalid => f.write_str(MSG_CSRF_INVALID),
39            Self::Custom { message, .. } => f.write_str(message),
40        }
41    }
42}
43
44/// Implements [`Error`] for [`SecurityViolation`].
45impl Error for SecurityViolation {}
46
47/// Default construction for [`SecurityHeadersConfig`].
48impl Default for SecurityHeadersConfig {
49    /// Constructs baseline modern HTTP security headers suitable for most services.
50    fn default() -> Self {
51        Self {
52            hsts: Some(DEFAULT_HSTS_VALUE.to_owned()),
53            content_security_policy: None,
54            x_frame_options: Some(DEFAULT_X_FRAME_OPTIONS.to_owned()),
55            x_content_type_options: Some(DEFAULT_X_CONTENT_TYPE_OPTIONS.to_owned()),
56            referrer_policy: Some(DEFAULT_REFERRER_POLICY.to_owned()),
57            permissions_policy: Some(DEFAULT_PERMISSIONS_POLICY.to_owned()),
58            coop: Some(DEFAULT_COOP_VALUE.to_owned()),
59            coep: None,
60            corp: Some(DEFAULT_CORP_VALUE.to_owned()),
61            remove_powered_by: true,
62        }
63    }
64}
65
66/// Inherent presets for [`SecurityHeadersConfig`].
67impl SecurityHeadersConfig {
68    /// Builds a strict browser-hardened header preset including strict CSP and COEP.
69    ///
70    /// # Returns
71    ///
72    /// - `Self` - Strict security headers configuration.
73    pub fn strict() -> Self {
74        Self {
75            hsts: Some(DEFAULT_HSTS_VALUE.to_owned()),
76            content_security_policy: Some(DEFAULT_CSP_STRICT.to_owned()),
77            x_frame_options: Some(DEFAULT_X_FRAME_OPTIONS.to_owned()),
78            x_content_type_options: Some(DEFAULT_X_CONTENT_TYPE_OPTIONS.to_owned()),
79            referrer_policy: Some(DEFAULT_REFERRER_POLICY.to_owned()),
80            permissions_policy: Some(DEFAULT_PERMISSIONS_POLICY.to_owned()),
81            coop: Some(DEFAULT_COOP_VALUE.to_owned()),
82            coep: Some(DEFAULT_COEP_VALUE.to_owned()),
83            corp: Some(DEFAULT_CORP_VALUE.to_owned()),
84            remove_powered_by: true,
85        }
86    }
87
88    /// Prebuilds a flat `(header_name, value)` vector for zero-allocation hot-path injection.
89    ///
90    /// # Returns
91    ///
92    /// - `Vec<(&'static str, String)>` - Compiled static header pairs.
93    pub(crate) fn compile(&self) -> Vec<(&'static str, String)> {
94        let mut out: Vec<(&'static str, String)> = Vec::with_capacity(9);
95        if let Some(val) = self.get_hsts() {
96            out.push((STRICT_TRANSPORT_SECURITY, val));
97        }
98        if let Some(val) = self.get_content_security_policy() {
99            out.push((CONTENT_SECURITY_POLICY, val));
100        }
101        if let Some(val) = self.get_x_frame_options() {
102            out.push((X_FRAME_OPTIONS, val));
103        }
104        if let Some(val) = self.get_x_content_type_options() {
105            out.push((X_CONTENT_TYPE_OPTIONS, val));
106        }
107        if let Some(val) = self.get_referrer_policy() {
108            out.push((REFERRER_POLICY, val));
109        }
110        if let Some(val) = self.get_permissions_policy() {
111            out.push((PERMISSIONS_POLICY, val));
112        }
113        if let Some(val) = self.get_coop() {
114            out.push((CROSS_ORIGIN_OPENER_POLICY, val));
115        }
116        if let Some(val) = self.get_coep() {
117            out.push((CROSS_ORIGIN_EMBEDDER_POLICY, val));
118        }
119        if let Some(val) = self.get_corp() {
120            out.push((CROSS_ORIGIN_RESOURCE_POLICY, val));
121        }
122        out
123    }
124}
125
126/// Default construction for [`CsrfConfig`].
127impl Default for CsrfConfig {
128    /// Constructs a disabled [`CsrfConfig`] with standard cookie and header names.
129    fn default() -> Self {
130        Self {
131            enabled: false,
132            secret: Vec::new(),
133            cookie_name: DEFAULT_CSRF_COOKIE_NAME.to_owned(),
134            header_name: DEFAULT_CSRF_HEADER_NAME.to_owned(),
135            exempt_paths: Vec::new(),
136        }
137    }
138}
139
140/// Inherent constructors for [`CsrfConfig`].
141impl CsrfConfig {
142    /// Builds an enabled [`CsrfConfig`] using `secret` for stateless HMAC-SHA256 signing.
143    ///
144    /// # Arguments
145    ///
146    /// - `S` - Secret key bytes convertible into `Vec<u8>`.
147    ///
148    /// # Returns
149    ///
150    /// - `Self` - Enabled CSRF configuration.
151    pub fn enabled<S>(secret: S) -> Self
152    where
153        S: Into<Vec<u8>>,
154    {
155        Self {
156            enabled: true,
157            secret: secret.into(),
158            cookie_name: DEFAULT_CSRF_COOKIE_NAME.to_owned(),
159            header_name: DEFAULT_CSRF_HEADER_NAME.to_owned(),
160            exempt_paths: Vec::new(),
161        }
162    }
163}
164
165/// Default construction for [`RequestGuardConfig`].
166impl Default for RequestGuardConfig {
167    /// Constructs a [`RequestGuardConfig`] blocking path traversal and oversized URIs.
168    fn default() -> Self {
169        Self {
170            max_body_bytes: DEFAULT_SECURITY_MAX_BODY_BYTES,
171            max_uri_bytes: DEFAULT_MAX_URI_BYTES,
172            allowed_hosts: Vec::new(),
173            block_path_traversal: true,
174        }
175    }
176}
177
178/// Inherent presets and builders for [`SecurityConfig`].
179impl SecurityConfig {
180    /// Builds a strict browser-hardened [`SecurityConfig`] preset.
181    ///
182    /// # Returns
183    ///
184    /// - `Self` - Strict security configuration.
185    pub fn strict() -> Self {
186        Self {
187            headers: SecurityHeadersConfig::strict(),
188            csrf: CsrfConfig::default(),
189            guard: RequestGuardConfig::default(),
190        }
191    }
192
193    /// Sets the [`SecurityHeadersConfig`].
194    ///
195    /// # Arguments
196    ///
197    /// - `SecurityHeadersConfig` - Header settings.
198    ///
199    /// # Returns
200    ///
201    /// - `Self` - Updated configuration.
202    pub fn with_headers(mut self, headers: SecurityHeadersConfig) -> Self {
203        self.set_headers(headers);
204        self
205    }
206
207    /// Sets the [`CsrfConfig`].
208    ///
209    /// # Arguments
210    ///
211    /// - `CsrfConfig` - CSRF protection settings.
212    ///
213    /// # Returns
214    ///
215    /// - `Self` - Updated configuration.
216    pub fn with_csrf(mut self, csrf: CsrfConfig) -> Self {
217        self.set_csrf(csrf);
218        self
219    }
220
221    /// Sets the [`RequestGuardConfig`].
222    ///
223    /// # Arguments
224    ///
225    /// - `RequestGuardConfig` - Request guard settings.
226    ///
227    /// # Returns
228    ///
229    /// - `Self` - Updated configuration.
230    pub fn with_guard(mut self, guard: RequestGuardConfig) -> Self {
231        self.set_guard(guard);
232        self
233    }
234}
235
236/// Inherent implementation of [`SecurityPlugin`].
237impl SecurityPlugin {
238    /// Compiles a standalone [`SecurityPlugin`] instance (useful for direct invocation or testing).
239    ///
240    /// # Arguments
241    ///
242    /// - `SecurityConfig` - Security headers, CSRF, and guard settings.
243    /// - `Vec<SharedSecurityRule>` - Additional custom security inspection rules.
244    ///
245    /// # Returns
246    ///
247    /// - `Self` - Compiled security engine.
248    pub fn new(config: SecurityConfig, rules: Vec<SharedSecurityRule>) -> Self {
249        let compiled_headers: Vec<(&'static str, String)> = config.get_headers().compile();
250        let csrf_hmac_key: Option<HmacSha256Key> = if config.get_csrf().get_enabled() {
251            Some(precompute_hmac_sha256_key(config.get_csrf().get_secret()))
252        } else {
253            None
254        };
255        let csrf_header_lower: String = config.get_csrf().get_header_name().to_ascii_lowercase();
256        Self {
257            config,
258            compiled_headers: Arc::new(compiled_headers),
259            rules: Arc::new(rules),
260            csrf_hmac_key,
261            csrf_header_lower,
262        }
263    }
264
265    /// Initializes the global [`SecurityPlugin`] once with `config`.
266    ///
267    /// # Arguments
268    ///
269    /// - `SecurityConfig` - Security hardening configuration.
270    ///
271    /// # Returns
272    ///
273    /// - `&'static Self` - Reference to the initialized global plugin.
274    pub fn init(config: SecurityConfig) -> &'static Self {
275        Self::init_with_rules(config, Vec::new())
276    }
277
278    /// Initializes the global [`SecurityPlugin`] once with `config` and custom [`SecurityRule`] hooks.
279    ///
280    /// # Arguments
281    ///
282    /// - `SecurityConfig` - Security hardening configuration.
283    /// - `Vec<SharedSecurityRule>` - Custom request security rules.
284    ///
285    /// # Returns
286    ///
287    /// - `&'static Self` - Reference to the initialized global plugin.
288    pub fn init_with_rules(
289        config: SecurityConfig,
290        rules: Vec<SharedSecurityRule>,
291    ) -> &'static Self {
292        SECURITY_PLUGIN.get_or_init(|| Self::new(config, rules))
293    }
294
295    /// Returns the initialized global [`SecurityPlugin`], if initialized.
296    ///
297    /// # Returns
298    ///
299    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
300    pub fn get() -> Option<&'static Self> {
301        SECURITY_PLUGIN.get()
302    }
303
304    /// Returns the active [`SecurityConfig`].
305    ///
306    /// # Returns
307    ///
308    /// - `&SecurityConfig` - Active configuration.
309    pub fn get_config(&self) -> &SecurityConfig {
310        &self.config
311    }
312
313    /// Evaluates request guards, double-submit HMAC CSRF protection, and custom rules on `ctx`.
314    ///
315    /// # Arguments
316    ///
317    /// - `&Context` - Incoming request context.
318    ///
319    /// # Returns
320    ///
321    /// - `Result<(), SecurityViolation>` - `Ok(())` when all checks pass.
322    pub fn inspect_request(&self, ctx: &Context) -> Result<(), SecurityViolation> {
323        let Self {
324            config,
325            rules,
326            csrf_hmac_key,
327            csrf_header_lower,
328            ..
329        } = self;
330        let guard: &RequestGuardConfig = config.get_guard();
331        let request: &Request = ctx.get_request();
332        let path: &str = request.get_path();
333        if guard.get_max_uri_bytes() > 0 && path.len() > guard.get_max_uri_bytes() {
334            return Err(SecurityViolation::UriTooLong);
335        }
336        if guard.get_max_body_bytes() > 0 && request.get_body().len() > guard.get_max_body_bytes() {
337            return Err(SecurityViolation::BodyTooLarge);
338        }
339        if guard.get_block_path_traversal() && has_path_traversal(path) {
340            return Err(SecurityViolation::PathTraversal);
341        }
342        if !guard.get_allowed_hosts().is_empty() {
343            let host_ok: bool =
344                get_request_header_back_ref(request, HOST).is_some_and(|incoming: &str| {
345                    let trimmed: &str = incoming.trim();
346                    guard
347                        .get_allowed_hosts()
348                        .iter()
349                        .any(|allowed: &String| allowed.eq_ignore_ascii_case(trimmed))
350                });
351            if !host_ok {
352                return Err(SecurityViolation::InvalidHost);
353            }
354        }
355        let csrf: &CsrfConfig = config.get_csrf();
356        if csrf.get_enabled()
357            && !is_csrf_safe_method(request.get_method())
358            && !csrf
359                .get_exempt_paths()
360                .iter()
361                .any(|exempt: &String| exempt == path)
362        {
363            let Some(header_token) = get_request_header_back_ref(request, csrf_header_lower) else {
364                return Err(SecurityViolation::CsrfInvalid);
365            };
366            let Some(raw_cookie) = get_request_header_back_ref(request, COOKIE) else {
367                return Err(SecurityViolation::CsrfInvalid);
368            };
369            let Some(cookie_token) = find_cookie_value(raw_cookie, csrf.get_cookie_name()) else {
370                return Err(SecurityViolation::CsrfInvalid);
371            };
372            if !constant_time_eq(header_token.as_bytes(), cookie_token.as_bytes()) {
373                return Err(SecurityViolation::CsrfInvalid);
374            }
375            let sig_ok: bool = if let Some(pre) = csrf_hmac_key {
376                verify_csrf_token_with_key(pre, header_token)
377            } else {
378                verify_csrf_token(csrf.get_secret(), header_token)
379            };
380            if !sig_ok {
381                return Err(SecurityViolation::CsrfInvalid);
382            }
383        }
384        for rule in rules.iter() {
385            rule.inspect(ctx)?;
386        }
387        Ok(())
388    }
389
390    /// Applies prebuilt security headers onto `response` and optionally strips `X-Powered-By`.
391    ///
392    /// # Arguments
393    ///
394    /// - `&mut Response` - Outgoing HTTP response.
395    #[inline]
396    pub fn apply_headers(&self, response: &mut Response) {
397        let Self {
398            config,
399            compiled_headers,
400            ..
401        } = self;
402        let headers_slice: &[(&'static str, String)] = compiled_headers.as_slice();
403        if response.get_headers().is_empty() {
404            for (name, value) in headers_slice {
405                response.set_header(*name, value);
406            }
407            return;
408        }
409        for (name, value) in headers_slice {
410            if !response.has_header(*name) {
411                response.set_header(*name, value);
412            }
413        }
414        if config.get_headers().get_remove_powered_by() {
415            response.remove_header(X_POWERED_BY);
416        }
417    }
418}
419
420/// Implements [`ServerHook`] for [`SecurityRequestHook`].
421impl ServerHook for SecurityRequestHook {
422    /// Constructs a per-request [`SecurityRequestHook`].
423    ///
424    /// # Arguments
425    ///
426    /// - `&mut Stream` - Connection stream.
427    /// - `&mut Context` - Request context.
428    ///
429    /// # Returns
430    ///
431    /// - `Self` - Hook instance.
432    async fn new(_: &mut Stream, _: &mut Context) -> Self {
433        Self
434    }
435
436    /// Enforces request security guards, CSRF validation, and custom rules, and seeds response security headers.
437    ///
438    /// # Arguments
439    ///
440    /// - `Self` - Hook instance.
441    /// - `&mut Stream` - Connection stream.
442    /// - `&mut Context` - Request context.
443    ///
444    /// # Returns
445    ///
446    /// - `Status` - `Status::Continue` when permitted; `Status::Reject` after sending an error response on violation.
447    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
448        let Some(plugin) = SecurityPlugin::get() else {
449            return Status::Continue;
450        };
451        plugin.apply_headers(ctx.get_mut_response());
452        if let Err(violation) = plugin.inspect_request(ctx) {
453            ctx.get_mut_response()
454                .set_status_code(violation.status_code())
455                .set_body(Vec::new());
456            let wire: ResponseData = ctx.get_mut_response().build();
457            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
458            return Status::Reject;
459        }
460        Status::Continue
461    }
462}
463
464/// Implements [`ServerHook`] for [`SecurityResponseHook`].
465impl ServerHook for SecurityResponseHook {
466    /// Constructs a per-response [`SecurityResponseHook`].
467    ///
468    /// # Arguments
469    ///
470    /// - `&mut Stream` - Connection stream.
471    /// - `&mut Context` - Request context.
472    ///
473    /// # Returns
474    ///
475    /// - `Self` - Hook instance.
476    async fn new(_: &mut Stream, _: &mut Context) -> Self {
477        Self
478    }
479
480    /// Ensures configured security headers remain present and removes `X-Powered-By`.
481    ///
482    /// # Arguments
483    ///
484    /// - `Self` - Hook instance.
485    /// - `&mut Stream` - Connection stream.
486    /// - `&mut Context` - Request context.
487    ///
488    /// # Returns
489    ///
490    /// - `Status` - Always `Status::Continue`.
491    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
492        let Some(plugin) = SecurityPlugin::get() else {
493            return Status::Continue;
494        };
495        plugin.apply_headers(ctx.get_mut_response());
496        Status::Continue
497    }
498}