Skip to main content

hyperlane_plugin_rewrite/
impl.rs

1use super::*;
2
3/// Formats [`RewriteError`] for display diagnostics.
4impl Display for RewriteError {
5    /// Renders a human-readable rewrite compilation error.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting outcome.
14    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
24/// Marks [`RewriteError`] as a standard error type.
25impl error::Error for RewriteError {}
26
27/// Inherent status-code mapping for [`RedirectStatus`].
28impl RedirectStatus {
29    /// Converts this redirect variant into its numeric HTTP status code (`301`/`302`/`307`/`308`).
30    ///
31    /// # Returns
32    ///
33    /// - `usize` - Numeric HTTP status code.
34    #[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
45/// Default construction for [`RewriteConfig`].
46impl Default for RewriteConfig {
47    /// Constructs a no-op default [`RewriteConfig`] preserving incoming host, scheme, and path.
48    ///
49    /// # Returns
50    ///
51    /// - `Self` - Default configuration.
52    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
68/// Fluent configuration builders for [`RewriteConfig`].
69impl RewriteConfig {
70    /// Enables or disables redirecting non-HTTPS requests to `https://`.
71    ///
72    /// # Arguments
73    ///
74    /// - `bool` - Whether HTTPS is enforced.
75    ///
76    /// # Returns
77    ///
78    /// - `Self` - Updated configuration.
79    pub fn with_force_https(mut self, force_https: bool) -> Self {
80        self.set_force_https(force_https);
81        self
82    }
83
84    /// Sets the canonical host (for example `"example.com"`), redirecting mismatches in a single hop.
85    ///
86    /// # Arguments
87    ///
88    /// - `S` - Canonical host value.
89    ///
90    /// # Returns
91    ///
92    /// - `Self` - Updated configuration.
93    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    /// Sets the redirect status code used for canonical host and HTTPS redirects.
102    ///
103    /// # Arguments
104    ///
105    /// - `RedirectStatus` - Redirect HTTP status (`301`/`302`/`307`/`308`).
106    ///
107    /// # Returns
108    ///
109    /// - `Self` - Updated configuration.
110    pub fn with_canonical_redirect_status(mut self, status: RedirectStatus) -> Self {
111        self.set_canonical_redirect_status(status);
112        self
113    }
114
115    /// Enables or disables trusting `X-Forwarded-Proto` and `Forwarded` when detecting HTTPS.
116    ///
117    /// # Arguments
118    ///
119    /// - `bool` - Whether forwarded protocol headers are trusted.
120    ///
121    /// # Returns
122    ///
123    /// - `Self` - Updated configuration.
124    pub fn with_trust_forwarded_proto(mut self, trust: bool) -> Self {
125        self.set_trust_forwarded_proto(trust);
126        self
127    }
128
129    /// Enables or disables collapsing consecutive duplicate slashes (`"//"` -> `"/"`).
130    ///
131    /// # Arguments
132    ///
133    /// - `bool` - Whether duplicate slashes are collapsed.
134    ///
135    /// # Returns
136    ///
137    /// - `Self` - Updated configuration.
138    pub fn with_collapse_duplicate_slashes(mut self, collapse: bool) -> Self {
139        self.set_collapse_duplicate_slashes(collapse);
140        self
141    }
142
143    /// Configures trailing-slash normalization (`Keep`, `Strip`, or `Enforce`) and its [`RewriteAction`].
144    ///
145    /// # Arguments
146    ///
147    /// - `TrailingSlashMode` - Desired trailing-slash policy.
148    /// - `RewriteAction` - Whether normalization rewrites internally or redirects.
149    ///
150    /// # Returns
151    ///
152    /// - `Self` - Updated configuration.
153    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    /// Adds an `O(1)` exact-path internal rewrite rule (`from` -> `to`).
160    ///
161    /// # Arguments
162    ///
163    /// - `F` - Exact incoming path.
164    /// - `T` - Rewritten internal path.
165    ///
166    /// # Returns
167    ///
168    /// - `Self` - Updated configuration.
169    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    /// Adds an `O(1)` exact-path short-circuit HTTP redirect rule (`from` -> `to`).
184    ///
185    /// # Arguments
186    ///
187    /// - `F` - Exact incoming path.
188    /// - `T` - Redirect destination path or URL.
189    /// - `RedirectStatus` - Redirect HTTP status code.
190    ///
191    /// # Returns
192    ///
193    /// - `Self` - Updated configuration.
194    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    /// Adds a segment-bounded prefix strip rule (for example `"/api/v1"` strips `"/api/v1"` internally).
209    ///
210    /// # Arguments
211    ///
212    /// - `F` - Incoming path prefix to strip.
213    ///
214    /// # Returns
215    ///
216    /// - `Self` - Updated configuration.
217    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    /// Adds a segment-bounded prefix rewrite or redirect rule (`from` -> `to`).
231    ///
232    /// # Arguments
233    ///
234    /// - `F` - Incoming path prefix.
235    /// - `T` - Replacement prefix.
236    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
237    ///
238    /// # Returns
239    ///
240    /// - `Self` - Updated configuration.
241    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    /// Adds a regular-expression rewrite or redirect rule supporting capture replacements (`$1`, `$2`).
256    ///
257    /// # Arguments
258    ///
259    /// - `P` - Regular expression pattern.
260    /// - `R` - Replacement template.
261    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
262    ///
263    /// # Returns
264    ///
265    /// - `Self` - Updated configuration.
266    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
286/// Inherent compilation and hot-path request evaluation for [`CompiledRewrite`].
287impl CompiledRewrite {
288    /// Compiles and validates `config` into `O(1)` hash tables and precompiled regex engines.
289    ///
290    /// # Arguments
291    ///
292    /// - `RewriteConfig` - Source rewrite configuration.
293    ///
294    /// # Returns
295    ///
296    /// - `Result<Self, RewriteError>` - Compiled rewrite engine or validation/regex error.
297    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    /// Returns the source [`RewriteConfig`].
377    ///
378    /// # Returns
379    ///
380    /// - `&RewriteConfig` - Active configuration.
381    pub fn get_config(&self) -> &RewriteConfig {
382        let Self { config, .. } = self;
383        config
384    }
385
386    /// Evaluates canonical host/HTTPS, path normalization, exact, prefix, and regex rules against `ctx`.
387    ///
388    /// On an internal rewrite, updates `ctx.get_mut_request().set_path(...)` and stores the original
389    /// path under [`ATTR_ORIGINAL_PATH`]. On a redirect, populates `ctx.get_mut_response()` with the
390    /// redirect status code and sanitized `Location` header.
391    ///
392    /// # Arguments
393    ///
394    /// - `&mut Context` - Active Hyperlane request/response context.
395    ///
396    /// # Returns
397    ///
398    /// - `RewriteOutcome` - Whether the request was unchanged, rewritten internally, or redirected.
399    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
546/// Process-wide singleton management for [`RewritePlugin`].
547impl RewritePlugin {
548    /// Compiles `config` and initializes the global [`RewritePlugin`] once.
549    ///
550    /// # Arguments
551    ///
552    /// - `RewriteConfig` - Rewrite and redirect configuration.
553    ///
554    /// # Returns
555    ///
556    /// - `Result<&'static Self, RewriteError>` - Reference to the initialized global plugin or compilation error.
557    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    /// Returns the initialized global [`RewritePlugin`], if initialized.
563    ///
564    /// # Returns
565    ///
566    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
567    #[inline]
568    pub fn get() -> Option<&'static Self> {
569        REWRITE_PLUGIN.get()
570    }
571
572    /// Returns the compiled [`CompiledRewrite`] engine.
573    ///
574    /// # Returns
575    ///
576    /// - `&CompiledRewrite` - Precompiled rewrite engine.
577    #[inline]
578    pub fn get_compiled(&self) -> &CompiledRewrite {
579        let Self { compiled } = self;
580        compiled
581    }
582}
583
584/// Implements [`ServerHook`] for [`RewriteHook`].
585impl ServerHook for RewriteHook {
586    /// Constructs a per-request [`RewriteHook`].
587    ///
588    /// # Arguments
589    ///
590    /// - `&mut Stream` - Connection stream.
591    /// - `&mut Context` - Request context.
592    ///
593    /// # Returns
594    ///
595    /// - `Self` - Hook instance.
596    async fn new(_: &mut Stream, _: &mut Context) -> Self {
597        Self
598    }
599
600    /// Applies rewrite/redirect rules, short-circuiting on HTTP redirects or continuing on rewrites.
601    ///
602    /// # Arguments
603    ///
604    /// - `Self` - Hook instance.
605    /// - `&mut Stream` - Connection stream.
606    /// - `&mut Context` - Request context.
607    ///
608    /// # Returns
609    ///
610    /// - `Status` - `Status::Reject` after sending redirect bytes; `Status::Continue` otherwise.
611    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}