hyperlane_plugin_security/
impl.rs1use super::*;
2
3impl SecurityViolation {
5 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
21impl Display for SecurityViolation {
23 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
44impl Error for SecurityViolation {}
46
47impl Default for SecurityHeadersConfig {
49 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
66impl SecurityHeadersConfig {
68 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 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
126impl Default for CsrfConfig {
128 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
140impl CsrfConfig {
142 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
165impl Default for RequestGuardConfig {
167 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
178impl SecurityConfig {
180 pub fn strict() -> Self {
186 Self {
187 headers: SecurityHeadersConfig::strict(),
188 csrf: CsrfConfig::default(),
189 guard: RequestGuardConfig::default(),
190 }
191 }
192
193 pub fn with_headers(mut self, headers: SecurityHeadersConfig) -> Self {
203 self.set_headers(headers);
204 self
205 }
206
207 pub fn with_csrf(mut self, csrf: CsrfConfig) -> Self {
217 self.set_csrf(csrf);
218 self
219 }
220
221 pub fn with_guard(mut self, guard: RequestGuardConfig) -> Self {
231 self.set_guard(guard);
232 self
233 }
234}
235
236impl SecurityPlugin {
238 pub fn new(config: SecurityConfig, rules: Vec<SharedSecurityRule>) -> Self {
249 let compiled_headers: Vec<(&'static str, String)> = config.get_headers().compile();
250 Self {
251 config,
252 compiled_headers: Arc::new(compiled_headers),
253 rules: Arc::new(rules),
254 }
255 }
256
257 pub fn init(config: SecurityConfig) -> &'static Self {
267 Self::init_with_rules(config, Vec::new())
268 }
269
270 pub fn init_with_rules(
281 config: SecurityConfig,
282 rules: Vec<SharedSecurityRule>,
283 ) -> &'static Self {
284 SECURITY_PLUGIN.get_or_init(|| Self::new(config, rules))
285 }
286
287 pub fn get() -> Option<&'static Self> {
293 SECURITY_PLUGIN.get()
294 }
295
296 pub fn get_config(&self) -> &SecurityConfig {
302 &self.config
303 }
304
305 pub fn inspect_request(&self, ctx: &Context) -> Result<(), SecurityViolation> {
315 let Self { config, rules, .. } = self;
316 let guard: &RequestGuardConfig = config.get_guard();
317 let path: &str = ctx.get_request().get_path();
318 if guard.get_max_uri_bytes() > 0 && path.len() > guard.get_max_uri_bytes() {
319 return Err(SecurityViolation::UriTooLong);
320 }
321 if guard.get_max_body_bytes() > 0
322 && ctx.get_request().get_body().len() > guard.get_max_body_bytes()
323 {
324 return Err(SecurityViolation::BodyTooLarge);
325 }
326 if guard.get_block_path_traversal() && has_path_traversal(path) {
327 return Err(SecurityViolation::PathTraversal);
328 }
329 if !guard.get_allowed_hosts().is_empty() {
330 let host_ok: bool =
331 ctx.get_request()
332 .try_get_header_back(HOST)
333 .is_some_and(|incoming: String| {
334 let trimmed: &str = incoming.trim();
335 guard
336 .get_allowed_hosts()
337 .iter()
338 .any(|allowed: &String| allowed.eq_ignore_ascii_case(trimmed))
339 });
340 if !host_ok {
341 return Err(SecurityViolation::InvalidHost);
342 }
343 }
344 let csrf: &CsrfConfig = config.get_csrf();
345 if csrf.get_enabled()
346 && !is_csrf_safe_method(ctx.get_request().get_method())
347 && !csrf
348 .get_exempt_paths()
349 .iter()
350 .any(|exempt: &String| exempt == path)
351 {
352 let Some(header_token) = ctx
353 .get_request()
354 .try_get_header_back(csrf.get_header_name())
355 else {
356 return Err(SecurityViolation::CsrfInvalid);
357 };
358 let Some(raw_cookie) = ctx.get_request().try_get_header_back(COOKIE) else {
359 return Err(SecurityViolation::CsrfInvalid);
360 };
361 let cookies: Cookies = Cookie::parse(raw_cookie);
362 let Some(cookie_token) = cookies.get(csrf.get_cookie_name()) else {
363 return Err(SecurityViolation::CsrfInvalid);
364 };
365 if !constant_time_eq(header_token.as_bytes(), cookie_token.as_bytes())
366 || !verify_csrf_token(csrf.get_secret(), &header_token)
367 {
368 return Err(SecurityViolation::CsrfInvalid);
369 }
370 }
371 for rule in rules.iter() {
372 rule.inspect(ctx)?;
373 }
374 Ok(())
375 }
376
377 pub fn apply_headers(&self, response: &mut Response) {
383 let Self {
384 config,
385 compiled_headers,
386 ..
387 } = self;
388 for (name, value) in compiled_headers.iter() {
389 if response.try_get_header_back(*name).is_none() {
390 response.set_header(*name, value);
391 }
392 }
393 if config.get_headers().get_remove_powered_by() {
394 response.remove_header(X_POWERED_BY);
395 }
396 }
397}
398
399impl ServerHook for SecurityRequestHook {
401 async fn new(_: &mut Stream, _: &mut Context) -> Self {
412 Self
413 }
414
415 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
427 let Some(plugin) = SecurityPlugin::get() else {
428 return Status::Continue;
429 };
430 plugin.apply_headers(ctx.get_mut_response());
431 if let Err(violation) = plugin.inspect_request(ctx) {
432 ctx.get_mut_response()
433 .set_status_code(violation.status_code())
434 .set_body(Vec::new());
435 let wire: ResponseData = ctx.get_mut_response().build();
436 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
437 return Status::Reject;
438 }
439 Status::Continue
440 }
441}
442
443impl ServerHook for SecurityResponseHook {
445 async fn new(_: &mut Stream, _: &mut Context) -> Self {
456 Self
457 }
458
459 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
471 let Some(plugin) = SecurityPlugin::get() else {
472 return Status::Continue;
473 };
474 plugin.apply_headers(ctx.get_mut_response());
475 Status::Continue
476 }
477}