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 validated `(header_name, value)` vector for zero-overhead hot-path injection.
89    ///
90    /// # Returns
91    ///
92    /// - `Vec<(&'static str, String)>` - Compiled validated 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            && is_valid_header_value(&val)
97        {
98            out.push((STRICT_TRANSPORT_SECURITY, val));
99        }
100        if let Some(val) = self.get_content_security_policy()
101            && is_valid_header_value(&val)
102        {
103            out.push((CONTENT_SECURITY_POLICY, val));
104        }
105        if let Some(val) = self.get_x_frame_options()
106            && is_valid_header_value(&val)
107        {
108            out.push((X_FRAME_OPTIONS, val));
109        }
110        if let Some(val) = self.get_x_content_type_options()
111            && is_valid_header_value(&val)
112        {
113            out.push((X_CONTENT_TYPE_OPTIONS, val));
114        }
115        if let Some(val) = self.get_referrer_policy()
116            && is_valid_header_value(&val)
117        {
118            out.push((REFERRER_POLICY, val));
119        }
120        if let Some(val) = self.get_permissions_policy()
121            && is_valid_header_value(&val)
122        {
123            out.push((PERMISSIONS_POLICY, val));
124        }
125        if let Some(val) = self.get_coop()
126            && is_valid_header_value(&val)
127        {
128            out.push((CROSS_ORIGIN_OPENER_POLICY, val));
129        }
130        if let Some(val) = self.get_coep()
131            && is_valid_header_value(&val)
132        {
133            out.push((CROSS_ORIGIN_EMBEDDER_POLICY, val));
134        }
135        if let Some(val) = self.get_corp()
136            && is_valid_header_value(&val)
137        {
138            out.push((CROSS_ORIGIN_RESOURCE_POLICY, val));
139        }
140        out
141    }
142}
143
144/// Default construction for [`CsrfConfig`].
145impl Default for CsrfConfig {
146    /// Constructs a disabled [`CsrfConfig`] with standard cookie and header names.
147    fn default() -> Self {
148        Self {
149            enabled: false,
150            secret: Vec::new(),
151            cookie_name: DEFAULT_CSRF_COOKIE_NAME.to_owned(),
152            header_name: DEFAULT_CSRF_HEADER_NAME.to_owned(),
153            exempt_paths: Vec::new(),
154        }
155    }
156}
157
158/// Inherent constructors for [`CsrfConfig`].
159impl CsrfConfig {
160    /// Builds an enabled [`CsrfConfig`] using `secret` for stateless HMAC-SHA256 signing.
161    ///
162    /// # Arguments
163    ///
164    /// - `S` - Secret key bytes convertible into `Vec<u8>`.
165    ///
166    /// # Returns
167    ///
168    /// - `Self` - Enabled CSRF configuration.
169    pub fn enabled<S>(secret: S) -> Self
170    where
171        S: Into<Vec<u8>>,
172    {
173        Self {
174            enabled: true,
175            secret: secret.into(),
176            cookie_name: DEFAULT_CSRF_COOKIE_NAME.to_owned(),
177            header_name: DEFAULT_CSRF_HEADER_NAME.to_owned(),
178            exempt_paths: Vec::new(),
179        }
180    }
181}
182
183/// Default construction for [`RequestGuardConfig`].
184impl Default for RequestGuardConfig {
185    /// Constructs a [`RequestGuardConfig`] blocking path traversal and oversized URIs.
186    fn default() -> Self {
187        Self {
188            max_body_bytes: DEFAULT_SECURITY_MAX_BODY_BYTES,
189            max_uri_bytes: DEFAULT_MAX_URI_BYTES,
190            allowed_hosts: Vec::new(),
191            block_path_traversal: true,
192        }
193    }
194}
195
196/// Inherent presets and builders for [`SecurityConfig`].
197impl SecurityConfig {
198    /// Builds a strict browser-hardened [`SecurityConfig`] preset.
199    ///
200    /// # Returns
201    ///
202    /// - `Self` - Strict security configuration.
203    pub fn strict() -> Self {
204        Self {
205            headers: SecurityHeadersConfig::strict(),
206            csrf: CsrfConfig::default(),
207            guard: RequestGuardConfig::default(),
208        }
209    }
210
211    /// Sets the [`SecurityHeadersConfig`].
212    ///
213    /// # Arguments
214    ///
215    /// - `SecurityHeadersConfig` - Header settings.
216    ///
217    /// # Returns
218    ///
219    /// - `Self` - Updated configuration.
220    pub fn with_headers(mut self, headers: SecurityHeadersConfig) -> Self {
221        self.set_headers(headers);
222        self
223    }
224
225    /// Sets the [`CsrfConfig`].
226    ///
227    /// # Arguments
228    ///
229    /// - `CsrfConfig` - CSRF protection settings.
230    ///
231    /// # Returns
232    ///
233    /// - `Self` - Updated configuration.
234    pub fn with_csrf(mut self, csrf: CsrfConfig) -> Self {
235        self.set_csrf(csrf);
236        self
237    }
238
239    /// Sets the [`RequestGuardConfig`].
240    ///
241    /// # Arguments
242    ///
243    /// - `RequestGuardConfig` - Request guard settings.
244    ///
245    /// # Returns
246    ///
247    /// - `Self` - Updated configuration.
248    pub fn with_guard(mut self, guard: RequestGuardConfig) -> Self {
249        self.set_guard(guard);
250        self
251    }
252}
253
254/// Inherent implementation of [`SecurityPlugin`].
255impl SecurityPlugin {
256    /// Compiles a standalone [`SecurityPlugin`] instance (useful for direct invocation or testing).
257    ///
258    /// # Arguments
259    ///
260    /// - `SecurityConfig` - Security headers, CSRF, and guard settings.
261    /// - `Vec<Arc<dyn SecurityRule>>` - Additional custom security inspection rules.
262    ///
263    /// # Returns
264    ///
265    /// - `Self` - Compiled security engine.
266    pub fn new(config: SecurityConfig, rules: Vec<Arc<dyn SecurityRule>>) -> Self {
267        let compiled_headers: Vec<(&'static str, String)> = config.get_headers().compile();
268        let csrf_hmac_key: Option<HmacSha256Key> = if config.get_csrf().get_enabled() {
269            Some(precompute_hmac_sha256_key(config.get_csrf().get_secret()))
270        } else {
271            None
272        };
273        let csrf_header_lower: String = config.get_csrf().get_header_name().to_ascii_lowercase();
274        let csrf_cookie_name_valid: bool =
275            is_valid_cookie_name(config.get_csrf().get_cookie_name());
276        Self {
277            config,
278            compiled_headers: Arc::new(compiled_headers),
279            rules: Arc::new(rules),
280            csrf_hmac_key,
281            csrf_header_lower,
282            csrf_cookie_name_valid,
283        }
284    }
285
286    /// Initializes the global [`SecurityPlugin`] once with `config`.
287    ///
288    /// # Arguments
289    ///
290    /// - `SecurityConfig` - Security hardening configuration.
291    ///
292    /// # Returns
293    ///
294    /// - `&'static Self` - Reference to the initialized global plugin.
295    pub fn init(config: SecurityConfig) -> &'static Self {
296        Self::init_with_rules(config, Vec::new())
297    }
298
299    /// Initializes the global [`SecurityPlugin`] once with `config` and custom [`SecurityRule`] hooks.
300    ///
301    /// # Arguments
302    ///
303    /// - `SecurityConfig` - Security hardening configuration.
304    /// - `Vec<Arc<dyn SecurityRule>>` - Custom request security rules.
305    ///
306    /// # Returns
307    ///
308    /// - `&'static Self` - Reference to the initialized global plugin.
309    pub fn init_with_rules(
310        config: SecurityConfig,
311        rules: Vec<Arc<dyn SecurityRule>>,
312    ) -> &'static Self {
313        SECURITY_PLUGIN.get_or_init(|| Self::new(config, rules))
314    }
315
316    /// Returns the initialized global [`SecurityPlugin`], if initialized.
317    ///
318    /// # Returns
319    ///
320    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
321    pub fn get() -> Option<&'static Self> {
322        SECURITY_PLUGIN.get()
323    }
324
325    /// Returns the active [`SecurityConfig`].
326    ///
327    /// # Returns
328    ///
329    /// - `&SecurityConfig` - Active configuration.
330    pub fn get_config(&self) -> &SecurityConfig {
331        let Self { config, .. } = self;
332        config
333    }
334
335    /// Evaluates request guards, double-submit HMAC CSRF protection, and custom rules on `ctx`.
336    ///
337    /// # Arguments
338    ///
339    /// - `&Context` - Incoming request context.
340    ///
341    /// # Returns
342    ///
343    /// - `Result<(), SecurityViolation>` - `Ok(())` when all checks pass.
344    pub fn inspect_request(&self, ctx: &Context) -> Result<(), SecurityViolation> {
345        let Self {
346            config,
347            rules,
348            csrf_hmac_key,
349            csrf_header_lower,
350            csrf_cookie_name_valid,
351            ..
352        } = self;
353        let guard: &RequestGuardConfig = config.get_guard();
354        let request: &Request = ctx.get_request();
355        let path: &str = request.get_path();
356        if guard.get_max_uri_bytes() > 0 && path.len() > guard.get_max_uri_bytes() {
357            return Err(SecurityViolation::UriTooLong);
358        }
359        if guard.get_max_body_bytes() > 0 && request.get_body().len() > guard.get_max_body_bytes() {
360            return Err(SecurityViolation::BodyTooLarge);
361        }
362        if guard.get_block_path_traversal() && has_path_traversal(path) {
363            return Err(SecurityViolation::PathTraversal);
364        }
365        if !guard.get_allowed_hosts().is_empty() {
366            let host_ok: bool =
367                get_request_header_back_ref(request, HOST).is_some_and(|incoming: &str| {
368                    let trimmed: &str = incoming.trim();
369                    guard
370                        .get_allowed_hosts()
371                        .iter()
372                        .any(|allowed: &String| allowed.eq_ignore_ascii_case(trimmed))
373                });
374            if !host_ok {
375                return Err(SecurityViolation::InvalidHost);
376            }
377        }
378        let csrf: &CsrfConfig = config.get_csrf();
379        if csrf.get_enabled()
380            && !is_csrf_safe_method(request.get_method())
381            && !csrf
382                .get_exempt_paths()
383                .iter()
384                .any(|exempt: &String| exempt == path)
385        {
386            let Some(header_token) = get_request_header_back_ref(request, csrf_header_lower) else {
387                return Err(SecurityViolation::CsrfInvalid);
388            };
389            let Some(raw_cookie) = get_request_header_back_ref(request, COOKIE) else {
390                return Err(SecurityViolation::CsrfInvalid);
391            };
392            let Some(cookie_token) =
393                find_cookie_value(raw_cookie, csrf.get_cookie_name(), *csrf_cookie_name_valid)
394            else {
395                return Err(SecurityViolation::CsrfInvalid);
396            };
397            if !constant_time_eq(header_token.as_bytes(), cookie_token.as_bytes()) {
398                return Err(SecurityViolation::CsrfInvalid);
399            }
400            let sig_ok: bool = if let Some(pre) = csrf_hmac_key {
401                verify_csrf_token_with_key(pre, header_token)
402            } else {
403                verify_csrf_token(csrf.get_secret(), header_token)
404            };
405            if !sig_ok {
406                return Err(SecurityViolation::CsrfInvalid);
407            }
408        }
409        for rule in rules.iter() {
410            rule.inspect(ctx)?;
411        }
412        Ok(())
413    }
414
415    /// Applies prebuilt validated security headers onto `response` and optionally strips `X-Powered-By`.
416    ///
417    /// # Arguments
418    ///
419    /// - `&mut Response` - Outgoing HTTP response.
420    #[inline]
421    pub fn apply_headers(&self, response: &mut Response) {
422        let Self {
423            config,
424            compiled_headers,
425            ..
426        } = self;
427        let headers_slice: &[(&'static str, String)] = compiled_headers.as_slice();
428        if response.get_headers().is_empty() {
429            response.set_headers_batch(headers_slice);
430            return;
431        }
432        let mut missing: [(&str, &str); 16] = [("", ""); 16];
433        let mut missing_len: usize = 0;
434        for (name, value) in headers_slice {
435            if !response.get_headers().contains_key(*name) {
436                if missing_len < missing.len() {
437                    missing[missing_len] = (*name, value.as_str());
438                    missing_len += 1;
439                } else {
440                    response.set_header(*name, value.as_str());
441                }
442            }
443        }
444        if missing_len > 0 {
445            response.set_headers_batch(&missing[..missing_len]);
446        }
447        if config.get_headers().get_remove_powered_by() {
448            let _: Option<VecDeque<String>> = response.get_mut_headers().remove(X_POWERED_BY);
449        }
450    }
451}
452
453/// Implements [`ServerHook`] for [`SecurityRequestHook`].
454impl ServerHook for SecurityRequestHook {
455    /// Constructs a per-request [`SecurityRequestHook`].
456    ///
457    /// # Arguments
458    ///
459    /// - `&mut Stream` - Connection stream.
460    /// - `&mut Context` - Request context.
461    ///
462    /// # Returns
463    ///
464    /// - `Self` - Hook instance.
465    async fn new(_: &mut Stream, _: &mut Context) -> Self {
466        Self
467    }
468
469    /// Enforces request security guards, CSRF validation, and custom rules, and seeds response security headers.
470    ///
471    /// # Arguments
472    ///
473    /// - `Self` - Hook instance.
474    /// - `&mut Stream` - Connection stream.
475    /// - `&mut Context` - Request context.
476    ///
477    /// # Returns
478    ///
479    /// - `Status` - `Status::Continue` when permitted; `Status::Reject` after sending an error response on violation.
480    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
481        let Some(plugin) = SecurityPlugin::get() else {
482            return Status::Continue;
483        };
484        plugin.apply_headers(ctx.get_mut_response());
485        if let Err(violation) = plugin.inspect_request(ctx) {
486            ctx.get_mut_response()
487                .set_status_code(violation.status_code())
488                .set_body(Vec::new());
489            let _: Result<(), ResponseError> = ctx.try_send_response(stream).await;
490            return Status::Reject;
491        }
492        Status::Continue
493    }
494}
495
496/// Implements [`ServerHook`] for [`SecurityResponseHook`].
497impl ServerHook for SecurityResponseHook {
498    /// Constructs a per-response [`SecurityResponseHook`].
499    ///
500    /// # Arguments
501    ///
502    /// - `&mut Stream` - Connection stream.
503    /// - `&mut Context` - Request context.
504    ///
505    /// # Returns
506    ///
507    /// - `Self` - Hook instance.
508    async fn new(_: &mut Stream, _: &mut Context) -> Self {
509        Self
510    }
511
512    /// Ensures configured security headers remain present and removes `X-Powered-By`.
513    ///
514    /// # Arguments
515    ///
516    /// - `Self` - Hook instance.
517    /// - `&mut Stream` - Connection stream.
518    /// - `&mut Context` - Request context.
519    ///
520    /// # Returns
521    ///
522    /// - `Status` - Always `Status::Continue`.
523    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
524        let Some(plugin) = SecurityPlugin::get() else {
525            return Status::Continue;
526        };
527        plugin.apply_headers(ctx.get_mut_response());
528        Status::Continue
529    }
530}