Skip to main content

hyperlane_plugin_rewrite/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`FxHasher`] with zero allocations and 8-byte word mixing.
4impl Hasher for FxHasher {
5    /// Finalizes the 64-bit hash state.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Finalized 64-bit hash.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { state } = *self;
13        state
14    }
15
16    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Input byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { state } = self;
24        let mut h: u64 = *state;
25        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
26        for chunk in chunks {
27            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
28        }
29        let mut tail: &[u8] = rem;
30        if tail.len() >= 4 {
31            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
32            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
33            tail = &tail[4..];
34        }
35        if tail.len() >= 2 {
36            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
37            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
38            tail = &tail[2..];
39        }
40        if let Some(&b) = tail.first() {
41            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
42        }
43        *state = h;
44    }
45
46    /// Mixes a single `u8` delimiter byte without slice overhead.
47    ///
48    /// # Arguments
49    ///
50    /// - `u8` - Input byte.
51    #[inline(always)]
52    fn write_u8(&mut self, i: u8) {
53        let Self { state } = self;
54        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
55    }
56}
57
58/// Formats [`RewriteError`] for display diagnostics.
59impl Display for RewriteError {
60    /// Renders a human-readable rewrite compilation error.
61    ///
62    /// # Arguments
63    ///
64    /// - `&mut Formatter<'_>` - Output formatter.
65    ///
66    /// # Returns
67    ///
68    /// - `fmt::Result` - Formatting outcome.
69    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
70        match self {
71            Self::InvalidRegex { pattern, message } => {
72                write!(f, "{ERR_INVALID_REGEX} `{pattern}`: {message}")
73            }
74            Self::UnsafeLocation(raw) => write!(f, "{ERR_UNSAFE_LOCATION}: {raw:?}"),
75        }
76    }
77}
78
79/// Marks [`RewriteError`] as a standard error type.
80impl error::Error for RewriteError {}
81
82/// Inherent status-code mapping for [`RedirectStatus`].
83impl RedirectStatus {
84    /// Converts this redirect variant into its numeric HTTP status code (`301`/`302`/`307`/`308`).
85    ///
86    /// # Returns
87    ///
88    /// - `usize` - Numeric HTTP status code.
89    #[inline]
90    pub fn code(self) -> usize {
91        match self {
92            Self::MovedPermanently301 => HttpStatus::MovedPermanently.code(),
93            Self::Found302 => HttpStatus::Found.code(),
94            Self::Temporary307 => HttpStatus::TemporaryRedirect.code(),
95            Self::Permanent308 => HttpStatus::PermanentRedirect.code(),
96        }
97    }
98}
99
100/// Default construction for [`RewriteConfig`].
101impl Default for RewriteConfig {
102    /// Constructs a no-op default [`RewriteConfig`] preserving incoming host, scheme, and path.
103    ///
104    /// # Returns
105    ///
106    /// - `Self` - Default configuration.
107    fn default() -> Self {
108        Self {
109            force_https: false,
110            canonical_host: None,
111            canonical_redirect_status: RedirectStatus::Permanent308,
112            trust_forwarded_proto: true,
113            collapse_duplicate_slashes: false,
114            trailing_slash: TrailingSlashMode::Keep,
115            normalization_action: RewriteAction::InternalRewrite,
116            exact_rules: Vec::new(),
117            prefix_rules: Vec::new(),
118            regex_rules: Vec::new(),
119        }
120    }
121}
122
123/// Fluent configuration builders for [`RewriteConfig`].
124impl RewriteConfig {
125    /// Enables or disables redirecting non-HTTPS requests to `https://`.
126    ///
127    /// # Arguments
128    ///
129    /// - `bool` - Whether HTTPS is enforced.
130    ///
131    /// # Returns
132    ///
133    /// - `Self` - Updated configuration.
134    pub fn with_force_https(mut self, force_https: bool) -> Self {
135        self.set_force_https(force_https);
136        self
137    }
138
139    /// Sets the canonical host (for example `"example.com"`), redirecting mismatches in a single hop.
140    ///
141    /// # Arguments
142    ///
143    /// - `S` - Canonical host value.
144    ///
145    /// # Returns
146    ///
147    /// - `Self` - Updated configuration.
148    pub fn with_canonical_host<S>(mut self, host: S) -> Self
149    where
150        S: Into<String>,
151    {
152        self.set_canonical_host(Some(host.into()));
153        self
154    }
155
156    /// Sets the redirect status code used for canonical host and HTTPS redirects.
157    ///
158    /// # Arguments
159    ///
160    /// - `RedirectStatus` - Redirect HTTP status (`301`/`302`/`307`/`308`).
161    ///
162    /// # Returns
163    ///
164    /// - `Self` - Updated configuration.
165    pub fn with_canonical_redirect_status(mut self, status: RedirectStatus) -> Self {
166        self.set_canonical_redirect_status(status);
167        self
168    }
169
170    /// Enables or disables trusting `X-Forwarded-Proto` and `Forwarded` when detecting HTTPS.
171    ///
172    /// # Arguments
173    ///
174    /// - `bool` - Whether forwarded protocol headers are trusted.
175    ///
176    /// # Returns
177    ///
178    /// - `Self` - Updated configuration.
179    pub fn with_trust_forwarded_proto(mut self, trust: bool) -> Self {
180        self.set_trust_forwarded_proto(trust);
181        self
182    }
183
184    /// Enables or disables collapsing consecutive duplicate slashes (`"//"` -> `"/"`).
185    ///
186    /// # Arguments
187    ///
188    /// - `bool` - Whether duplicate slashes are collapsed.
189    ///
190    /// # Returns
191    ///
192    /// - `Self` - Updated configuration.
193    pub fn with_collapse_duplicate_slashes(mut self, collapse: bool) -> Self {
194        self.set_collapse_duplicate_slashes(collapse);
195        self
196    }
197
198    /// Configures trailing-slash normalization (`Keep`, `Strip`, or `Enforce`) and its [`RewriteAction`].
199    ///
200    /// # Arguments
201    ///
202    /// - `TrailingSlashMode` - Desired trailing-slash policy.
203    /// - `RewriteAction` - Whether normalization rewrites internally or redirects.
204    ///
205    /// # Returns
206    ///
207    /// - `Self` - Updated configuration.
208    pub fn with_trailing_slash(mut self, mode: TrailingSlashMode, action: RewriteAction) -> Self {
209        self.set_trailing_slash(mode)
210            .set_normalization_action(action);
211        self
212    }
213
214    /// Adds an `O(1)` exact-path internal rewrite rule (`from` -> `to`).
215    ///
216    /// # Arguments
217    ///
218    /// - `F` - Exact incoming path.
219    /// - `T` - Rewritten internal path.
220    ///
221    /// # Returns
222    ///
223    /// - `Self` - Updated configuration.
224    pub fn with_exact_rewrite<F, T>(mut self, from: F, to: T) -> Self
225    where
226        F: Into<String>,
227        T: Into<String>,
228    {
229        self.get_mut_exact_rules().push(ExactRewriteRule {
230            from: from.into(),
231            to: to.into(),
232            action: RewriteAction::InternalRewrite,
233            preserve_query: true,
234        });
235        self
236    }
237
238    /// Adds an `O(1)` exact-path short-circuit HTTP redirect rule (`from` -> `to`).
239    ///
240    /// # Arguments
241    ///
242    /// - `F` - Exact incoming path.
243    /// - `T` - Redirect destination path or URL.
244    /// - `RedirectStatus` - Redirect HTTP status code.
245    ///
246    /// # Returns
247    ///
248    /// - `Self` - Updated configuration.
249    pub fn with_exact_redirect<F, T>(mut self, from: F, to: T, status: RedirectStatus) -> Self
250    where
251        F: Into<String>,
252        T: Into<String>,
253    {
254        self.get_mut_exact_rules().push(ExactRewriteRule {
255            from: from.into(),
256            to: to.into(),
257            action: RewriteAction::Redirect(status),
258            preserve_query: true,
259        });
260        self
261    }
262
263    /// Adds a segment-bounded prefix strip rule (for example `"/api/v1"` strips `"/api/v1"` internally).
264    ///
265    /// # Arguments
266    ///
267    /// - `F` - Incoming path prefix to strip.
268    ///
269    /// # Returns
270    ///
271    /// - `Self` - Updated configuration.
272    pub fn with_strip_prefix<F>(mut self, from: F) -> Self
273    where
274        F: Into<String>,
275    {
276        self.get_mut_prefix_rules().push(PrefixRewriteRule {
277            from: from.into(),
278            to: String::new(),
279            action: RewriteAction::InternalRewrite,
280            preserve_query: true,
281        });
282        self
283    }
284
285    /// Adds a segment-bounded prefix rewrite or redirect rule (`from` -> `to`).
286    ///
287    /// # Arguments
288    ///
289    /// - `F` - Incoming path prefix.
290    /// - `T` - Replacement prefix.
291    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
292    ///
293    /// # Returns
294    ///
295    /// - `Self` - Updated configuration.
296    pub fn with_prefix_rule<F, T>(mut self, from: F, to: T, action: RewriteAction) -> Self
297    where
298        F: Into<String>,
299        T: Into<String>,
300    {
301        self.get_mut_prefix_rules().push(PrefixRewriteRule {
302            from: from.into(),
303            to: to.into(),
304            action,
305            preserve_query: true,
306        });
307        self
308    }
309
310    /// Adds a regular-expression rewrite or redirect rule supporting capture replacements (`$1`, `$2`).
311    ///
312    /// # Arguments
313    ///
314    /// - `P` - Regular expression pattern.
315    /// - `R` - Replacement template.
316    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
317    ///
318    /// # Returns
319    ///
320    /// - `Self` - Updated configuration.
321    pub fn with_regex_rule<P, R>(
322        mut self,
323        pattern: P,
324        replacement: R,
325        action: RewriteAction,
326    ) -> Self
327    where
328        P: Into<String>,
329        R: Into<String>,
330    {
331        self.get_mut_regex_rules().push(RegexRewriteRule {
332            pattern: pattern.into(),
333            replacement: replacement.into(),
334            action,
335            preserve_query: true,
336        });
337        self
338    }
339}
340
341/// Inherent compilation and hot-path request evaluation for [`CompiledRewrite`].
342impl CompiledRewrite {
343    /// Compiles and validates `config` into `O(1)` zero-allocation hash tables and optimized matchers.
344    ///
345    /// # Arguments
346    ///
347    /// - `RewriteConfig` - Source rewrite configuration.
348    ///
349    /// # Returns
350    ///
351    /// - `Result<Self, RewriteError>` - Compiled rewrite engine or validation/regex error.
352    pub fn compile(config: RewriteConfig) -> Result<Self, RewriteError> {
353        let canonical_host_lower: Option<String> = match config.try_get_canonical_host() {
354            Some(host) => {
355                let trimmed: &str = host.trim();
356                if has_unsafe_header_chars(trimmed) {
357                    return Err(RewriteError::UnsafeLocation(trimmed.to_owned()));
358                }
359                if trimmed.is_empty() {
360                    None
361                } else {
362                    Some(trimmed.to_ascii_lowercase())
363                }
364            }
365            None => None,
366        };
367        let (canonical_https_origin, canonical_http_origin): (Option<String>, Option<String>) =
368            match canonical_host_lower.as_deref() {
369                Some(host) => {
370                    let mut https_origin: String = String::with_capacity(
371                        SCHEME_HTTPS.len() + SCHEME_SEPARATOR.len() + host.len(),
372                    );
373                    https_origin.push_str(SCHEME_HTTPS);
374                    https_origin.push_str(SCHEME_SEPARATOR);
375                    https_origin.push_str(host);
376                    let mut http_origin: String = String::with_capacity(
377                        SCHEME_HTTP.len() + SCHEME_SEPARATOR.len() + host.len(),
378                    );
379                    http_origin.push_str(SCHEME_HTTP);
380                    http_origin.push_str(SCHEME_SEPARATOR);
381                    http_origin.push_str(host);
382                    (Some(https_origin), Some(http_origin))
383                }
384                None => (None, None),
385            };
386        let mut exact_map: FxHashMap<String, CompiledExactTarget> =
387            HashMap::with_capacity_and_hasher(
388                config.get_exact_rules().len(),
389                BuildHasherDefault::default(),
390            );
391        for rule in config.get_exact_rules() {
392            let to_str: &str = rule.get_to();
393            if has_unsafe_header_chars(to_str) {
394                return Err(RewriteError::UnsafeLocation(to_str.to_owned()));
395            }
396            exact_map.insert(
397                rule.get_from().clone(),
398                CompiledExactTarget {
399                    has_query: to_str.as_bytes().contains(&BYTE_QUESTION),
400                    to: to_str.to_owned(),
401                    action: rule.get_action(),
402                    preserve_query: rule.get_preserve_query(),
403                },
404            );
405        }
406        let mut prefix_rules: Vec<CompiledPrefixRule> =
407            Vec::with_capacity(config.get_prefix_rules().len());
408        for rule in config.get_prefix_rules() {
409            let raw_to: &str = rule.get_to();
410            if has_unsafe_header_chars(raw_to) {
411                return Err(RewriteError::UnsafeLocation(raw_to.to_owned()));
412            }
413            let norm_from: String = normalize_rule_prefix(rule.get_from());
414            if norm_from.is_empty() {
415                continue;
416            }
417            let norm_to: String = if raw_to.is_empty() {
418                String::new()
419            } else {
420                normalize_rule_prefix(raw_to)
421            };
422            let to_has_query: bool = norm_to.as_bytes().contains(&BYTE_QUESTION);
423            prefix_rules.push(CompiledPrefixRule {
424                from: norm_from,
425                to: norm_to,
426                action: rule.get_action(),
427                preserve_query: rule.get_preserve_query(),
428                to_has_query,
429            });
430        }
431        prefix_rules.sort_by_key(|rule: &CompiledPrefixRule| Reverse(rule.from.len()));
432        let mut regex_rules: Vec<CompiledRegexRule> =
433            Vec::with_capacity(config.get_regex_rules().len());
434        let mut general_patterns: Vec<&str> = Vec::new();
435        for rule in config.get_regex_rules() {
436            let repl: &str = rule.get_replacement();
437            if has_unsafe_header_chars(repl) {
438                return Err(RewriteError::UnsafeLocation(repl.to_owned()));
439            }
440            let matcher: CompiledRegexMatcher =
441                if let Some(fast) = try_compile_fast_regex(rule.get_pattern(), repl) {
442                    fast
443                } else {
444                    let compiled_regex: Regex =
445                        Regex::new(rule.get_pattern()).map_err(|e: Error| {
446                            RewriteError::InvalidRegex {
447                                pattern: rule.get_pattern().clone(),
448                                message: e.to_string(),
449                            }
450                        })?;
451                    general_patterns.push(rule.get_pattern().as_str());
452                    CompiledRegexMatcher::General {
453                        regex: compiled_regex,
454                        replacement: repl.to_owned(),
455                        has_expand: repl.as_bytes().contains(&BYTE_DOLLAR),
456                    }
457                };
458            regex_rules.push(CompiledRegexRule {
459                matcher,
460                action: rule.get_action(),
461                preserve_query: rule.get_preserve_query(),
462            });
463        }
464        let general_regex_set: Option<RegexSet> = if general_patterns.len() >= 2 {
465            RegexSet::new(&general_patterns).ok()
466        } else {
467            None
468        };
469        Ok(Self {
470            config,
471            canonical_host_lower,
472            canonical_https_origin,
473            canonical_http_origin,
474            exact_map,
475            prefix_rules,
476            regex_rules,
477            general_regex_set,
478        })
479    }
480
481    /// Returns the source [`RewriteConfig`].
482    ///
483    /// # Returns
484    ///
485    /// - `&RewriteConfig` - Active configuration.
486    #[inline]
487    pub fn get_config(&self) -> &RewriteConfig {
488        let Self { config, .. } = self;
489        config
490    }
491
492    /// Evaluates regex rules using fast matchers and an optional combined `RegexSet` prefilter.
493    ///
494    /// # Arguments
495    ///
496    /// - `&str` - Normalized working path.
497    ///
498    /// # Returns
499    ///
500    /// - `Option<(String, RewriteAction, bool)>` - Matched replacement, action, and query preservation flag.
501    #[inline]
502    fn match_regex_rules(&self, working_path: &str) -> Option<(String, RewriteAction, bool)> {
503        let Self {
504            regex_rules,
505            general_regex_set,
506            ..
507        } = self;
508        let mut general_checked: bool = false;
509        let mut general_any_match: bool = true;
510        for rule in regex_rules {
511            if matches!(rule.matcher, CompiledRegexMatcher::General { .. }) {
512                if !general_checked {
513                    general_checked = true;
514                    if let Some(set) = general_regex_set {
515                        general_any_match = set.is_match(working_path);
516                    }
517                }
518                if !general_any_match {
519                    continue;
520                }
521            }
522            if let Some(replaced) = match_compiled_regex(&rule.matcher, working_path) {
523                return Some((replaced, rule.action, rule.preserve_query));
524            }
525        }
526        None
527    }
528
529    /// Evaluates canonical host/HTTPS, path normalization, exact, prefix, and regex rules against `ctx`.
530    ///
531    /// On an internal rewrite, updates `ctx.get_mut_request().set_path(...)` and stores the original
532    /// path under [`ATTR_ORIGINAL_PATH`]. On a redirect, populates `ctx.get_mut_response()` with the
533    /// redirect status code and sanitized `Location` header.
534    ///
535    /// # Arguments
536    ///
537    /// - `&mut Context` - Active Hyperlane request/response context.
538    ///
539    /// # Returns
540    ///
541    /// - `RewriteOutcome` - Whether the request was unchanged, rewritten internally, or redirected.
542    pub fn apply(&self, ctx: &mut Context) -> RewriteOutcome {
543        let Self {
544            config,
545            canonical_host_lower,
546            canonical_https_origin,
547            canonical_http_origin,
548            exact_map,
549            prefix_rules,
550            regex_rules,
551            ..
552        } = self;
553        if config.get_force_https() || canonical_host_lower.is_some() {
554            let headers: &RequestHeaders = ctx.get_request().get_headers();
555            let req_https: bool = is_request_https(headers, config.get_trust_forwarded_proto());
556            let needs_https: bool = config.get_force_https() && !req_https;
557            let req_host_ref: Option<&str> = find_header_back_ref(headers, HOST);
558            let needs_host_redirect: bool = match (canonical_host_lower.as_deref(), req_host_ref) {
559                (Some(canonical), Some(incoming)) => !host_matches_canonical(incoming, canonical),
560                (Some(_), None) => true,
561                (None, _) => false,
562            };
563            if needs_https || needs_host_redirect {
564                let use_https: bool = config.get_force_https() || req_https;
565                let prebuilt_origin: Option<&str> = if use_https {
566                    canonical_https_origin.as_deref()
567                } else {
568                    canonical_http_origin.as_deref()
569                };
570                let raw_path: &str = ctx.get_request().get_path();
571                let mut location: Option<String> = None;
572                if let Some(origin) = prebuilt_origin {
573                    let mut loc: String = String::with_capacity(origin.len() + raw_path.len() + 16);
574                    loc.push_str(origin);
575                    loc.push_str(raw_path);
576                    location = Some(loc);
577                } else if let Some(host) = req_host_ref
578                    && !host.is_empty()
579                    && !has_unsafe_header_chars(host)
580                {
581                    let scheme: &str = if use_https { SCHEME_HTTPS } else { SCHEME_HTTP };
582                    let mut loc: String = String::with_capacity(
583                        scheme.len() + SCHEME_SEPARATOR.len() + host.len() + raw_path.len() + 16,
584                    );
585                    loc.push_str(scheme);
586                    loc.push_str(SCHEME_SEPARATOR);
587                    loc.push_str(host);
588                    loc.push_str(raw_path);
589                    location = Some(loc);
590                }
591                if let Some(mut final_loc) = location {
592                    append_query_from_ctx(&mut final_loc, ctx, true, false);
593                    let status_code: usize = config.get_canonical_redirect_status().code();
594                    let resp: &mut Response = ctx.get_mut_response();
595                    resp.set_status_code(status_code)
596                        .set_header(LOCATION, &final_loc)
597                        .set_body(Vec::new());
598                    return RewriteOutcome::Redirected {
599                        status_code,
600                        location: final_loc,
601                    };
602                }
603            }
604        }
605        let original_path: &str = ctx.get_request().get_path();
606        let after_slash: Cow<'_, str> = if config.get_collapse_duplicate_slashes() {
607            collapse_slashes(original_path)
608        } else {
609            Cow::Borrowed(original_path)
610        };
611        let slash_collapsed: bool = matches!(after_slash, Cow::Owned(_));
612        let (normalized_path, trailing_changed): (Cow<'_, str>, bool) =
613            normalize_trailing_slash_borrowed(after_slash, config.get_trailing_slash());
614        let normalized_changed: bool = slash_collapsed || trailing_changed;
615        if normalized_changed
616            && let RewriteAction::Redirect(status) = config.get_normalization_action()
617        {
618            let mut location: String = normalized_path.into_owned();
619            if !has_unsafe_header_chars(&location) {
620                let has_q: bool = location.as_bytes().contains(&BYTE_QUESTION);
621                append_query_from_ctx(&mut location, ctx, true, has_q);
622                let status_code: usize = status.code();
623                ctx.get_mut_response()
624                    .set_status_code(status_code)
625                    .set_header(LOCATION, &location)
626                    .set_body(Vec::new());
627                return RewriteOutcome::Redirected {
628                    status_code,
629                    location,
630                };
631            }
632            return RewriteOutcome::Unchanged;
633        }
634        let working_path: &str = normalized_path.as_ref();
635        if !exact_map.is_empty()
636            && let Some(hit) = exact_map.get(working_path)
637        {
638            match hit.action {
639                RewriteAction::Redirect(status) => {
640                    let location: String =
641                        clone_with_query_from_ctx(&hit.to, ctx, hit.preserve_query, hit.has_query);
642                    let status_code: usize = status.code();
643                    ctx.get_mut_response()
644                        .set_status_code(status_code)
645                        .set_header(LOCATION, &location)
646                        .set_body(Vec::new());
647                    return RewriteOutcome::Redirected {
648                        status_code,
649                        location,
650                    };
651                }
652                RewriteAction::InternalRewrite => {
653                    let target: String = hit.to.clone();
654                    apply_internal_rewrite_copy(ctx, &target);
655                    return RewriteOutcome::Rewritten(target);
656                }
657            }
658        }
659        let mut matched: Option<(String, RewriteAction, bool, bool)> = None;
660        for rule in prefix_rules {
661            if let Some(rest) = strip_prefix_segment(working_path, &rule.from) {
662                let replaced: String = join_prefix_replacement(&rule.to, rest);
663                let has_q: bool = rule.to_has_query || rest.as_bytes().contains(&BYTE_QUESTION);
664                matched = Some((replaced, rule.action, rule.preserve_query, has_q));
665                break;
666            }
667        }
668        if matched.is_none()
669            && !regex_rules.is_empty()
670            && let Some((replaced, action, preserve_query)) = self.match_regex_rules(working_path)
671        {
672            let has_q: bool = replaced.as_bytes().contains(&BYTE_QUESTION);
673            matched = Some((replaced, action, preserve_query, has_q));
674        }
675        if let Some((mut target, action, preserve_query, has_q)) = matched {
676            match action {
677                RewriteAction::Redirect(status) => {
678                    if has_unsafe_header_chars(&target) {
679                        return RewriteOutcome::Unchanged;
680                    }
681                    append_query_from_ctx(&mut target, ctx, preserve_query, has_q);
682                    let status_code: usize = status.code();
683                    ctx.get_mut_response()
684                        .set_status_code(status_code)
685                        .set_header(LOCATION, &target)
686                        .set_body(Vec::new());
687                    return RewriteOutcome::Redirected {
688                        status_code,
689                        location: target,
690                    };
691                }
692                RewriteAction::InternalRewrite => {
693                    apply_internal_rewrite_copy(ctx, &target);
694                    return RewriteOutcome::Rewritten(target);
695                }
696            }
697        }
698        if normalized_changed {
699            let new_path: String = normalized_path.into_owned();
700            apply_internal_rewrite_copy(ctx, &new_path);
701            return RewriteOutcome::Rewritten(new_path);
702        }
703        RewriteOutcome::Unchanged
704    }
705
706    /// Evaluates rewrite rules for [`RewriteHook`] without cloning discarded outcome strings and sends redirects directly on HTTP/1.1.
707    ///
708    /// # Arguments
709    ///
710    /// - `&mut Stream` - Active client connection stream.
711    /// - `&mut Context` - Active Hyperlane request/response context.
712    ///
713    /// # Returns
714    ///
715    /// - `Status` - `Status::Reject` when a redirect was sent; `Status::Continue` otherwise.
716    #[inline]
717    pub(crate) async fn apply_and_send_hook(
718        &self,
719        stream: &mut Stream,
720        ctx: &mut Context,
721    ) -> Status {
722        let Self {
723            config,
724            canonical_host_lower,
725            canonical_https_origin,
726            canonical_http_origin,
727            exact_map,
728            prefix_rules,
729            regex_rules,
730            ..
731        } = self;
732        let resp: &Response = ctx.get_response();
733        let can_fast_wire: bool = ctx.get_request().get_version().is_http1_1()
734            && resp.get_version().is_http1_1()
735            && resp.get_headers().is_empty()
736            && (resp.get_reason_phrase().is_empty() || resp.get_reason_phrase().as_str() == OK);
737        if config.get_force_https() || canonical_host_lower.is_some() {
738            let headers: &RequestHeaders = ctx.get_request().get_headers();
739            let req_https: bool = is_request_https(headers, config.get_trust_forwarded_proto());
740            let needs_https: bool = config.get_force_https() && !req_https;
741            let req_host_ref: Option<&str> = find_header_back_ref(headers, HOST);
742            let needs_host_redirect: bool = match (canonical_host_lower.as_deref(), req_host_ref) {
743                (Some(canonical), Some(incoming)) => !host_matches_canonical(incoming, canonical),
744                (Some(_), None) => true,
745                (None, _) => false,
746            };
747            if needs_https || needs_host_redirect {
748                let use_https: bool = config.get_force_https() || req_https;
749                let status: RedirectStatus = config.get_canonical_redirect_status();
750                let prebuilt_origin: Option<&str> = if use_https {
751                    canonical_https_origin.as_deref()
752                } else {
753                    canonical_http_origin.as_deref()
754                };
755                if can_fast_wire {
756                    let raw_path: &str = ctx.get_request().get_path();
757                    let wire_prefix: &[u8] = redirect_wire_prefix(status);
758                    let mut stack: [u8; REDIRECT_WIRE_STACK_CAP] = [0u8; REDIRECT_WIRE_STACK_CAP];
759                    let mut pos: usize = wire_prefix.len();
760                    let host_ok: bool = if let Some(origin) = prebuilt_origin {
761                        let ob: &[u8] = origin.as_bytes();
762                        let pb: &[u8] = raw_path.as_bytes();
763                        if pos + ob.len() + pb.len() + WIRE_HEADER_END.len()
764                            <= REDIRECT_WIRE_STACK_CAP
765                        {
766                            stack[..pos].copy_from_slice(wire_prefix);
767                            stack[pos..pos + ob.len()].copy_from_slice(ob);
768                            pos += ob.len();
769                            stack[pos..pos + pb.len()].copy_from_slice(pb);
770                            pos += pb.len();
771                            true
772                        } else {
773                            false
774                        }
775                    } else if let Some(host) = req_host_ref
776                        && !host.is_empty()
777                        && !has_unsafe_header_chars(host)
778                    {
779                        let scheme: &[u8] = if use_https {
780                            SCHEME_HTTPS.as_bytes()
781                        } else {
782                            SCHEME_HTTP.as_bytes()
783                        };
784                        let sep: &[u8] = SCHEME_SEPARATOR.as_bytes();
785                        let hb: &[u8] = host.as_bytes();
786                        let pb: &[u8] = raw_path.as_bytes();
787                        if pos
788                            + scheme.len()
789                            + sep.len()
790                            + hb.len()
791                            + pb.len()
792                            + WIRE_HEADER_END.len()
793                            <= REDIRECT_WIRE_STACK_CAP
794                        {
795                            stack[..pos].copy_from_slice(wire_prefix);
796                            stack[pos..pos + scheme.len()].copy_from_slice(scheme);
797                            pos += scheme.len();
798                            stack[pos..pos + sep.len()].copy_from_slice(sep);
799                            pos += sep.len();
800                            stack[pos..pos + hb.len()].copy_from_slice(hb);
801                            pos += hb.len();
802                            stack[pos..pos + pb.len()].copy_from_slice(pb);
803                            pos += pb.len();
804                            true
805                        } else {
806                            false
807                        }
808                    } else {
809                        false
810                    };
811                    if host_ok
812                        && let Some(end_q) = write_query_bytes_from_ctx(
813                            &mut stack[..REDIRECT_WIRE_STACK_CAP - WIRE_HEADER_END.len()],
814                            pos,
815                            ctx,
816                            true,
817                            false,
818                        )
819                        && is_valid_wire_header_value_bytes(&stack[wire_prefix.len()..end_q])
820                    {
821                        let total: usize = end_q + WIRE_HEADER_END.len();
822                        stack[end_q..total].copy_from_slice(WIRE_HEADER_END);
823                        let _: Result<(), ResponseError> = stream.try_send(&stack[..total]).await;
824                        return Status::Reject;
825                    }
826                }
827                if matches!(self.apply(ctx), RewriteOutcome::Redirected { .. }) {
828                    let wire: Vec<u8> = ctx.get_mut_response().build();
829                    let _: Result<(), ResponseError> = stream.try_send(&wire).await;
830                    return Status::Reject;
831                }
832                return Status::Continue;
833            }
834        }
835        let original_path: &str = ctx.get_request().get_path();
836        let after_slash: Cow<'_, str> = if config.get_collapse_duplicate_slashes() {
837            collapse_slashes(original_path)
838        } else {
839            Cow::Borrowed(original_path)
840        };
841        let slash_collapsed: bool = matches!(after_slash, Cow::Owned(_));
842        let (normalized_path, trailing_changed): (Cow<'_, str>, bool) =
843            normalize_trailing_slash_borrowed(after_slash, config.get_trailing_slash());
844        let normalized_changed: bool = slash_collapsed || trailing_changed;
845        if normalized_changed
846            && let RewriteAction::Redirect(status) = config.get_normalization_action()
847        {
848            let has_q: bool = normalized_path.as_bytes().contains(&BYTE_QUESTION);
849            if has_unsafe_header_chars(normalized_path.as_ref()) {
850                return Status::Continue;
851            }
852            if can_fast_wire {
853                let mut stack: [u8; REDIRECT_WIRE_STACK_CAP] = [0u8; REDIRECT_WIRE_STACK_CAP];
854                if let Some(total) = Self::format_redirect_wire_stack(
855                    ctx,
856                    status,
857                    normalized_path.as_ref(),
858                    true,
859                    has_q,
860                    &mut stack,
861                ) {
862                    let _: Result<(), ResponseError> = stream.try_send(&stack[..total]).await;
863                    return Status::Reject;
864                }
865            }
866            let target_owned: String = normalized_path.into_owned();
867            return Self::send_redirect_fallback(stream, ctx, status, target_owned, true, has_q)
868                .await;
869        }
870        let working_path: &str = normalized_path.as_ref();
871        if !exact_map.is_empty()
872            && let Some(hit) = exact_map.get(working_path)
873        {
874            match hit.action {
875                RewriteAction::Redirect(status) => {
876                    return Self::send_redirect_location(
877                        stream,
878                        ctx,
879                        status,
880                        &hit.to,
881                        hit.preserve_query,
882                        hit.has_query,
883                        can_fast_wire,
884                    )
885                    .await;
886                }
887                RewriteAction::InternalRewrite => {
888                    let target: String = hit.to.clone();
889                    apply_internal_rewrite_owned(ctx, target);
890                    return Status::Continue;
891                }
892            }
893        }
894        let mut matched: Option<(String, RewriteAction, bool, bool)> = None;
895        for rule in prefix_rules {
896            if let Some(rest) = strip_prefix_segment(working_path, &rule.from) {
897                let replaced: String = join_prefix_replacement(&rule.to, rest);
898                let has_q: bool = rule.to_has_query || rest.as_bytes().contains(&BYTE_QUESTION);
899                matched = Some((replaced, rule.action, rule.preserve_query, has_q));
900                break;
901            }
902        }
903        if matched.is_none()
904            && !regex_rules.is_empty()
905            && let Some((replaced, action, preserve_query)) = self.match_regex_rules(working_path)
906        {
907            let has_q: bool = replaced.as_bytes().contains(&BYTE_QUESTION);
908            matched = Some((replaced, action, preserve_query, has_q));
909        }
910        if let Some((target, action, preserve_query, has_q)) = matched {
911            match action {
912                RewriteAction::Redirect(status) => {
913                    if has_unsafe_header_chars(&target) {
914                        return Status::Continue;
915                    }
916                    return Self::send_redirect_location(
917                        stream,
918                        ctx,
919                        status,
920                        &target,
921                        preserve_query,
922                        has_q,
923                        can_fast_wire,
924                    )
925                    .await;
926                }
927                RewriteAction::InternalRewrite => {
928                    apply_internal_rewrite_owned(ctx, target);
929                    return Status::Continue;
930                }
931            }
932        }
933        if normalized_changed {
934            let new_path: String = normalized_path.into_owned();
935            apply_internal_rewrite_owned(ctx, new_path);
936        }
937        Status::Continue
938    }
939
940    /// Formats an HTTP/1.1 redirect wire response into `stack` with zero heap allocations.
941    ///
942    /// # Arguments
943    ///
944    /// - `&Context` - Active request context.
945    /// - `RedirectStatus` - Redirect HTTP status code.
946    /// - `&str` - Validated base redirect location.
947    /// - `bool` - Whether to append incoming query parameters.
948    /// - `bool` - Whether `base_location` already contains `'?'`.
949    /// - `&mut [u8; REDIRECT_WIRE_STACK_CAP]` - Destination stack wire buffer.
950    ///
951    /// # Returns
952    ///
953    /// - `Option<usize>` - Total wire bytes written when it fits in `stack`.
954    #[inline]
955    fn format_redirect_wire_stack(
956        ctx: &Context,
957        status: RedirectStatus,
958        base_location: &str,
959        preserve_query: bool,
960        target_has_query: bool,
961        stack: &mut [u8; REDIRECT_WIRE_STACK_CAP],
962    ) -> Option<usize> {
963        let wire_prefix: &[u8] = redirect_wire_prefix(status);
964        let loc_bytes: &[u8] = base_location.as_bytes();
965        let prefix_total: usize = wire_prefix.len() + loc_bytes.len();
966        if prefix_total + WIRE_HEADER_END.len() > REDIRECT_WIRE_STACK_CAP {
967            return None;
968        }
969        stack[..wire_prefix.len()].copy_from_slice(wire_prefix);
970        stack[wire_prefix.len()..prefix_total].copy_from_slice(loc_bytes);
971        let end_q: usize = write_query_bytes_from_ctx(
972            &mut stack[..REDIRECT_WIRE_STACK_CAP - WIRE_HEADER_END.len()],
973            prefix_total,
974            ctx,
975            preserve_query,
976            target_has_query,
977        )?;
978        if !is_valid_wire_header_value_bytes(&stack[wire_prefix.len()..end_q]) {
979            return None;
980        }
981        let total: usize = end_q + WIRE_HEADER_END.len();
982        stack[end_q..total].copy_from_slice(WIRE_HEADER_END);
983        Some(total)
984    }
985
986    /// Sends a redirect via full [`Response::build`] when stack wire fast path is ineligible.
987    ///
988    /// # Arguments
989    ///
990    /// - `&mut Stream` - Active client stream.
991    /// - `&mut Context` - Active request/response context.
992    /// - `RedirectStatus` - Redirect HTTP status code.
993    /// - `String` - Owned base redirect location.
994    /// - `bool` - Whether to append incoming query parameters.
995    /// - `bool` - Whether `location` already contains `'?'`.
996    ///
997    /// # Returns
998    ///
999    /// - `Status` - Always `Status::Reject`.
1000    #[inline]
1001    async fn send_redirect_fallback(
1002        stream: &mut Stream,
1003        ctx: &mut Context,
1004        status: RedirectStatus,
1005        mut location: String,
1006        preserve_query: bool,
1007        target_has_query: bool,
1008    ) -> Status {
1009        append_query_from_ctx(&mut location, ctx, preserve_query, target_has_query);
1010        let status_code: usize = status.code();
1011        ctx.get_mut_response()
1012            .set_status_code(status_code)
1013            .set_header(LOCATION, &location)
1014            .set_body(Vec::new());
1015        let wire: Vec<u8> = ctx.get_mut_response().build();
1016        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1017        Status::Reject
1018    }
1019
1020    /// Sends a redirect response for `base_location`, using a zero-allocation stack wire buffer on HTTP/1.1.
1021    ///
1022    /// # Arguments
1023    ///
1024    /// - `&mut Stream` - Active client stream.
1025    /// - `&mut Context` - Active request/response context.
1026    /// - `RedirectStatus` - Redirect HTTP status code.
1027    /// - `&str` - Validated base redirect location.
1028    /// - `bool` - Whether to append incoming query parameters.
1029    /// - `bool` - Whether `base_location` already contains `'?'`.
1030    /// - `bool` - Whether HTTP/1.1 stack wire fast path is eligible.
1031    ///
1032    /// # Returns
1033    ///
1034    /// - `Status` - Always `Status::Reject`.
1035    #[inline]
1036    async fn send_redirect_location(
1037        stream: &mut Stream,
1038        ctx: &mut Context,
1039        status: RedirectStatus,
1040        base_location: &str,
1041        preserve_query: bool,
1042        target_has_query: bool,
1043        can_fast_wire: bool,
1044    ) -> Status {
1045        if can_fast_wire {
1046            let mut stack: [u8; REDIRECT_WIRE_STACK_CAP] = [0u8; REDIRECT_WIRE_STACK_CAP];
1047            if let Some(total) = Self::format_redirect_wire_stack(
1048                ctx,
1049                status,
1050                base_location,
1051                preserve_query,
1052                target_has_query,
1053                &mut stack,
1054            ) {
1055                let _: Result<(), ResponseError> = stream.try_send(&stack[..total]).await;
1056                return Status::Reject;
1057            }
1058        }
1059        Self::send_redirect_fallback(
1060            stream,
1061            ctx,
1062            status,
1063            base_location.to_owned(),
1064            preserve_query,
1065            target_has_query,
1066        )
1067        .await
1068    }
1069}
1070
1071/// Process-wide singleton management for [`RewritePlugin`].
1072impl RewritePlugin {
1073    /// Compiles `config` and initializes the global [`RewritePlugin`] once.
1074    ///
1075    /// # Arguments
1076    ///
1077    /// - `RewriteConfig` - Rewrite and redirect configuration.
1078    ///
1079    /// # Returns
1080    ///
1081    /// - `Result<&'static Self, RewriteError>` - Reference to the initialized global plugin or compilation error.
1082    pub fn init(config: RewriteConfig) -> Result<&'static Self, RewriteError> {
1083        let compiled: CompiledRewrite = CompiledRewrite::compile(config)?;
1084        Ok(REWRITE_PLUGIN.get_or_init(|| Self { compiled }))
1085    }
1086
1087    /// Returns the initialized global [`RewritePlugin`], if initialized.
1088    ///
1089    /// # Returns
1090    ///
1091    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1092    #[inline]
1093    pub fn get() -> Option<&'static Self> {
1094        REWRITE_PLUGIN.get()
1095    }
1096
1097    /// Returns the compiled [`CompiledRewrite`] engine.
1098    ///
1099    /// # Returns
1100    ///
1101    /// - `&CompiledRewrite` - Precompiled rewrite engine.
1102    #[inline]
1103    pub fn get_compiled(&self) -> &CompiledRewrite {
1104        let Self { compiled } = self;
1105        compiled
1106    }
1107}
1108
1109/// Implements [`ServerHook`] for [`RewriteHook`].
1110impl ServerHook for RewriteHook {
1111    /// Constructs a per-request [`RewriteHook`].
1112    ///
1113    /// # Arguments
1114    ///
1115    /// - `&mut Stream` - Connection stream.
1116    /// - `&mut Context` - Request context.
1117    ///
1118    /// # Returns
1119    ///
1120    /// - `Self` - Hook instance.
1121    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1122        Self
1123    }
1124
1125    /// Applies rewrite/redirect rules, short-circuiting on HTTP redirects or continuing on rewrites.
1126    ///
1127    /// # Arguments
1128    ///
1129    /// - `Self` - Hook instance.
1130    /// - `&mut Stream` - Connection stream.
1131    /// - `&mut Context` - Request context.
1132    ///
1133    /// # Returns
1134    ///
1135    /// - `Status` - `Status::Reject` after sending redirect bytes; `Status::Continue` otherwise.
1136    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1137        let Some(plugin) = RewritePlugin::get() else {
1138            return Status::Continue;
1139        };
1140        plugin.get_compiled().apply_and_send_hook(stream, ctx).await
1141    }
1142}