hyperlane_plugin_rewrite/
impl.rs1use super::*;
2
3impl Display for RewriteError {
5 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15 match self {
16 Self::InvalidRegex { pattern, message } => {
17 write!(f, "{ERR_INVALID_REGEX} `{pattern}`: {message}")
18 }
19 Self::UnsafeLocation(raw) => write!(f, "{ERR_UNSAFE_LOCATION}: {raw:?}"),
20 }
21 }
22}
23
24impl error::Error for RewriteError {}
26
27impl RedirectStatus {
29 #[inline]
35 pub fn code(self) -> usize {
36 match self {
37 Self::MovedPermanently301 => HttpStatus::MovedPermanently.code(),
38 Self::Found302 => HttpStatus::Found.code(),
39 Self::Temporary307 => HttpStatus::TemporaryRedirect.code(),
40 Self::Permanent308 => HttpStatus::PermanentRedirect.code(),
41 }
42 }
43}
44
45impl Default for RewriteConfig {
47 fn default() -> Self {
53 Self {
54 force_https: false,
55 canonical_host: None,
56 canonical_redirect_status: RedirectStatus::Permanent308,
57 trust_forwarded_proto: true,
58 collapse_duplicate_slashes: false,
59 trailing_slash: TrailingSlashMode::Keep,
60 normalization_action: RewriteAction::InternalRewrite,
61 exact_rules: Vec::new(),
62 prefix_rules: Vec::new(),
63 regex_rules: Vec::new(),
64 }
65 }
66}
67
68impl RewriteConfig {
70 pub fn with_force_https(mut self, force_https: bool) -> Self {
80 self.set_force_https(force_https);
81 self
82 }
83
84 pub fn with_canonical_host<S>(mut self, host: S) -> Self
94 where
95 S: Into<String>,
96 {
97 self.set_canonical_host(Some(host.into()));
98 self
99 }
100
101 pub fn with_canonical_redirect_status(mut self, status: RedirectStatus) -> Self {
111 self.set_canonical_redirect_status(status);
112 self
113 }
114
115 pub fn with_trust_forwarded_proto(mut self, trust: bool) -> Self {
125 self.set_trust_forwarded_proto(trust);
126 self
127 }
128
129 pub fn with_collapse_duplicate_slashes(mut self, collapse: bool) -> Self {
139 self.set_collapse_duplicate_slashes(collapse);
140 self
141 }
142
143 pub fn with_trailing_slash(mut self, mode: TrailingSlashMode, action: RewriteAction) -> Self {
154 self.set_trailing_slash(mode)
155 .set_normalization_action(action);
156 self
157 }
158
159 pub fn with_exact_rewrite<F, T>(mut self, from: F, to: T) -> Self
170 where
171 F: Into<String>,
172 T: Into<String>,
173 {
174 self.get_mut_exact_rules().push(ExactRewriteRule {
175 from: from.into(),
176 to: to.into(),
177 action: RewriteAction::InternalRewrite,
178 preserve_query: true,
179 });
180 self
181 }
182
183 pub fn with_exact_redirect<F, T>(mut self, from: F, to: T, status: RedirectStatus) -> Self
195 where
196 F: Into<String>,
197 T: Into<String>,
198 {
199 self.get_mut_exact_rules().push(ExactRewriteRule {
200 from: from.into(),
201 to: to.into(),
202 action: RewriteAction::Redirect(status),
203 preserve_query: true,
204 });
205 self
206 }
207
208 pub fn with_strip_prefix<F>(mut self, from: F) -> Self
218 where
219 F: Into<String>,
220 {
221 self.get_mut_prefix_rules().push(PrefixRewriteRule {
222 from: from.into(),
223 to: String::new(),
224 action: RewriteAction::InternalRewrite,
225 preserve_query: true,
226 });
227 self
228 }
229
230 pub fn with_prefix_rule<F, T>(mut self, from: F, to: T, action: RewriteAction) -> Self
242 where
243 F: Into<String>,
244 T: Into<String>,
245 {
246 self.get_mut_prefix_rules().push(PrefixRewriteRule {
247 from: from.into(),
248 to: to.into(),
249 action,
250 preserve_query: true,
251 });
252 self
253 }
254
255 pub fn with_regex_rule<P, R>(
267 mut self,
268 pattern: P,
269 replacement: R,
270 action: RewriteAction,
271 ) -> Self
272 where
273 P: Into<String>,
274 R: Into<String>,
275 {
276 self.get_mut_regex_rules().push(RegexRewriteRule {
277 pattern: pattern.into(),
278 replacement: replacement.into(),
279 action,
280 preserve_query: true,
281 });
282 self
283 }
284}
285
286impl CompiledRewrite {
288 pub fn compile(config: RewriteConfig) -> Result<Self, RewriteError> {
298 let canonical_host_lower: Option<String> = match config.try_get_canonical_host() {
299 Some(host) => {
300 let trimmed: &str = host.trim();
301 if has_unsafe_header_chars(trimmed) {
302 return Err(RewriteError::UnsafeLocation(trimmed.to_owned()));
303 }
304 if trimmed.is_empty() {
305 None
306 } else {
307 Some(trimmed.to_ascii_lowercase())
308 }
309 }
310 None => None,
311 };
312 let mut exact_map: HashMapXxHash3_64<String, CompiledExactTarget> = hash_map_xx_hash3_64();
313 for rule in config.get_exact_rules() {
314 if has_unsafe_header_chars(rule.get_to()) {
315 return Err(RewriteError::UnsafeLocation(rule.get_to().clone()));
316 }
317 exact_map.insert(
318 rule.get_from().clone(),
319 CompiledExactTarget {
320 to: rule.get_to().clone(),
321 action: rule.get_action(),
322 preserve_query: rule.get_preserve_query(),
323 },
324 );
325 }
326 let mut prefix_rules: Vec<CompiledPrefixRule> =
327 Vec::with_capacity(config.get_prefix_rules().len());
328 for rule in config.get_prefix_rules() {
329 if has_unsafe_header_chars(rule.get_to()) {
330 return Err(RewriteError::UnsafeLocation(rule.get_to().clone()));
331 }
332 let norm_from: String = normalize_rule_prefix(rule.get_from());
333 if norm_from.is_empty() {
334 continue;
335 }
336 let norm_to: String = if rule.get_to().is_empty() {
337 String::new()
338 } else {
339 normalize_rule_prefix(rule.get_to())
340 };
341 prefix_rules.push(CompiledPrefixRule {
342 from: norm_from,
343 to: norm_to,
344 action: rule.get_action(),
345 preserve_query: rule.get_preserve_query(),
346 });
347 }
348 prefix_rules.sort_by_key(|rule: &CompiledPrefixRule| Reverse(rule.from.len()));
349 let mut regex_rules: Vec<CompiledRegexRule> =
350 Vec::with_capacity(config.get_regex_rules().len());
351 for rule in config.get_regex_rules() {
352 if has_unsafe_header_chars(rule.get_replacement()) {
353 return Err(RewriteError::UnsafeLocation(rule.get_replacement().clone()));
354 }
355 let compiled_regex: Regex =
356 Regex::new(rule.get_pattern()).map_err(|e: Error| RewriteError::InvalidRegex {
357 pattern: rule.get_pattern().clone(),
358 message: e.to_string(),
359 })?;
360 regex_rules.push(CompiledRegexRule {
361 regex: compiled_regex,
362 replacement: rule.get_replacement().clone(),
363 action: rule.get_action(),
364 preserve_query: rule.get_preserve_query(),
365 });
366 }
367 Ok(Self {
368 config,
369 canonical_host_lower,
370 exact_map,
371 prefix_rules,
372 regex_rules,
373 })
374 }
375
376 pub fn get_config(&self) -> &RewriteConfig {
382 let Self { config, .. } = self;
383 config
384 }
385
386 pub fn apply(&self, ctx: &mut Context) -> RewriteOutcome {
400 let Self {
401 config,
402 canonical_host_lower,
403 exact_map,
404 prefix_rules,
405 regex_rules,
406 } = self;
407 if config.get_force_https() || canonical_host_lower.is_some() {
408 let headers: &RequestHeaders = ctx.get_request().get_headers();
409 let req_https: bool = is_request_https(headers, config.get_trust_forwarded_proto());
410 let needs_https: bool = config.get_force_https() && !req_https;
411 let req_host_ref: Option<&str> = find_header_back_ref(headers, HOST);
412 let needs_host_redirect: bool = match (canonical_host_lower.as_deref(), req_host_ref) {
413 (Some(canonical), Some(incoming)) => !host_matches_canonical(incoming, canonical),
414 (Some(_), None) => true,
415 (None, _) => false,
416 };
417 if needs_https || needs_host_redirect {
418 let target_host: Option<&str> = canonical_host_lower.as_deref().or(req_host_ref);
419 if let Some(host) = target_host
420 && !host.is_empty()
421 && !has_unsafe_header_chars(host)
422 {
423 let scheme: &str = if config.get_force_https() || req_https {
424 SCHEME_HTTPS
425 } else {
426 SCHEME_HTTP
427 };
428 let raw_path: &str = ctx.get_request().get_path();
429 let query: Option<String> = extract_query_string(ctx);
430 let mut location: String = String::with_capacity(
431 scheme.len() + SCHEME_SEPARATOR.len() + host.len() + raw_path.len() + 16,
432 );
433 location.push_str(scheme);
434 location.push_str(SCHEME_SEPARATOR);
435 location.push_str(host);
436 location.push_str(raw_path);
437 let final_loc: String =
438 append_query_if_needed(location, query.as_deref(), true);
439 let status_code: usize = config.get_canonical_redirect_status().code();
440 let resp: &mut Response = ctx.get_mut_response();
441 resp.set_status_code(status_code)
442 .set_header(LOCATION, &final_loc)
443 .set_body(Vec::new());
444 return RewriteOutcome::Redirected {
445 status_code,
446 location: final_loc,
447 };
448 }
449 }
450 }
451 let original_path: &str = ctx.get_request().get_path();
452 let after_slash: Cow<'_, str> = if config.get_collapse_duplicate_slashes() {
453 collapse_slashes(original_path)
454 } else {
455 Cow::Borrowed(original_path)
456 };
457 let normalized_path: Cow<'_, str> =
458 match normalize_trailing_slash(after_slash.as_ref(), config.get_trailing_slash()) {
459 Cow::Borrowed(_) => after_slash,
460 Cow::Owned(s) => Cow::Owned(s),
461 };
462 let normalized_changed: bool = matches!(normalized_path, Cow::Owned(_));
463 if normalized_changed
464 && let RewriteAction::Redirect(status) = config.get_normalization_action()
465 {
466 let target: String = normalized_path.into_owned();
467 if !has_unsafe_header_chars(&target) {
468 let query: Option<String> = extract_query_string(ctx);
469 let location: String = append_query_if_needed(target, query.as_deref(), true);
470 let status_code: usize = status.code();
471 ctx.get_mut_response()
472 .set_status_code(status_code)
473 .set_header(LOCATION, &location)
474 .set_body(Vec::new());
475 return RewriteOutcome::Redirected {
476 status_code,
477 location,
478 };
479 }
480 return RewriteOutcome::Unchanged;
481 }
482 let working_path: &str = normalized_path.as_ref();
483 let matched: Option<(String, RewriteAction, bool)> = if !exact_map.is_empty()
484 && let Some(hit) = exact_map.get(working_path)
485 {
486 Some((hit.to.clone(), hit.action, hit.preserve_query))
487 } else {
488 let mut found: Option<(String, RewriteAction, bool)> = None;
489 for rule in prefix_rules {
490 if let Some(rest) = strip_prefix_segment(working_path, &rule.from) {
491 let replaced: String = join_prefix_replacement(&rule.to, rest);
492 found = Some((replaced, rule.action, rule.preserve_query));
493 break;
494 }
495 }
496 if found.is_none() {
497 for rule in regex_rules {
498 if let Cow::Owned(replaced) =
499 rule.regex.replace(working_path, rule.replacement.as_str())
500 {
501 found = Some((replaced, rule.action, rule.preserve_query));
502 break;
503 }
504 }
505 }
506 found
507 };
508 if let Some((target, action, preserve_query)) = matched {
509 match action {
510 RewriteAction::Redirect(status) => {
511 if has_unsafe_header_chars(&target) {
512 return RewriteOutcome::Unchanged;
513 }
514 let query: Option<String> = extract_query_string(ctx);
515 let location: String =
516 append_query_if_needed(target, query.as_deref(), preserve_query);
517 let status_code: usize = status.code();
518 ctx.get_mut_response()
519 .set_status_code(status_code)
520 .set_header(LOCATION, &location)
521 .set_body(Vec::new());
522 return RewriteOutcome::Redirected {
523 status_code,
524 location,
525 };
526 }
527 RewriteAction::InternalRewrite => {
528 let prev: String = original_path.to_owned();
529 ctx.set_attribute(ATTR_ORIGINAL_PATH, prev);
530 ctx.get_mut_request().set_path(target.clone());
531 return RewriteOutcome::Rewritten(target);
532 }
533 }
534 }
535 if normalized_changed {
536 let new_path: String = normalized_path.into_owned();
537 let prev: String = original_path.to_owned();
538 ctx.set_attribute(ATTR_ORIGINAL_PATH, prev);
539 ctx.get_mut_request().set_path(new_path.clone());
540 return RewriteOutcome::Rewritten(new_path);
541 }
542 RewriteOutcome::Unchanged
543 }
544}
545
546impl RewritePlugin {
548 pub fn init(config: RewriteConfig) -> Result<&'static Self, RewriteError> {
558 let compiled: CompiledRewrite = CompiledRewrite::compile(config)?;
559 Ok(REWRITE_PLUGIN.get_or_init(|| Self { compiled }))
560 }
561
562 #[inline]
568 pub fn get() -> Option<&'static Self> {
569 REWRITE_PLUGIN.get()
570 }
571
572 #[inline]
578 pub fn get_compiled(&self) -> &CompiledRewrite {
579 let Self { compiled } = self;
580 compiled
581 }
582}
583
584impl ServerHook for RewriteHook {
586 async fn new(_: &mut Stream, _: &mut Context) -> Self {
597 Self
598 }
599
600 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
612 let Some(plugin) = RewritePlugin::get() else {
613 return Status::Continue;
614 };
615 if matches!(
616 plugin.get_compiled().apply(ctx),
617 RewriteOutcome::Redirected { .. }
618 ) {
619 let wire: ResponseData = ctx.get_mut_response().build();
620 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
621 return Status::Reject;
622 }
623 Status::Continue
624 }
625}