hyperlane-plugin-rewrite 22.14.1

A high-performance HTTP URL rewrite and redirect plugin for the Hyperlane framework featuring canonical host/HTTPS enforcement (X-Forwarded-Proto aware), trailing-slash and duplicate-slash normalization, O(1) XxHash3_64 static tables, segment-bounded prefix rules, and compiled regex rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
use super::*;

/// Formats [`RewriteError`] for display diagnostics.
impl Display for RewriteError {
    /// Renders a human-readable rewrite compilation error.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidRegex { pattern, message } => {
                write!(f, "{ERR_INVALID_REGEX} `{pattern}`: {message}")
            }
            Self::UnsafeLocation(raw) => write!(f, "{ERR_UNSAFE_LOCATION}: {raw:?}"),
        }
    }
}

/// Marks [`RewriteError`] as a standard error type.
impl error::Error for RewriteError {}

/// Inherent status-code mapping for [`RedirectStatus`].
impl RedirectStatus {
    /// Converts this redirect variant into its numeric HTTP status code (`301`/`302`/`307`/`308`).
    ///
    /// # Returns
    ///
    /// - `usize` - Numeric HTTP status code.
    #[inline]
    pub fn code(self) -> usize {
        match self {
            Self::MovedPermanently301 => HttpStatus::MovedPermanently.code(),
            Self::Found302 => HttpStatus::Found.code(),
            Self::Temporary307 => HttpStatus::TemporaryRedirect.code(),
            Self::Permanent308 => HttpStatus::PermanentRedirect.code(),
        }
    }
}

/// Default construction for [`RewriteConfig`].
impl Default for RewriteConfig {
    /// Constructs a no-op default [`RewriteConfig`] preserving incoming host, scheme, and path.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            force_https: false,
            canonical_host: None,
            canonical_redirect_status: RedirectStatus::Permanent308,
            trust_forwarded_proto: true,
            collapse_duplicate_slashes: false,
            trailing_slash: TrailingSlashMode::Keep,
            normalization_action: RewriteAction::InternalRewrite,
            exact_rules: Vec::new(),
            prefix_rules: Vec::new(),
            regex_rules: Vec::new(),
        }
    }
}

/// Fluent configuration builders for [`RewriteConfig`].
impl RewriteConfig {
    /// Enables or disables redirecting non-HTTPS requests to `https://`.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether HTTPS is enforced.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_force_https(mut self, force_https: bool) -> Self {
        self.set_force_https(force_https);
        self
    }

    /// Sets the canonical host (for example `"example.com"`), redirecting mismatches in a single hop.
    ///
    /// # Arguments
    ///
    /// - `S` - Canonical host value.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_canonical_host<S>(mut self, host: S) -> Self
    where
        S: Into<String>,
    {
        self.set_canonical_host(Some(host.into()));
        self
    }

    /// Sets the redirect status code used for canonical host and HTTPS redirects.
    ///
    /// # Arguments
    ///
    /// - `RedirectStatus` - Redirect HTTP status (`301`/`302`/`307`/`308`).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_canonical_redirect_status(mut self, status: RedirectStatus) -> Self {
        self.set_canonical_redirect_status(status);
        self
    }

    /// Enables or disables trusting `X-Forwarded-Proto` and `Forwarded` when detecting HTTPS.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether forwarded protocol headers are trusted.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_trust_forwarded_proto(mut self, trust: bool) -> Self {
        self.set_trust_forwarded_proto(trust);
        self
    }

    /// Enables or disables collapsing consecutive duplicate slashes (`"//"` -> `"/"`).
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether duplicate slashes are collapsed.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_collapse_duplicate_slashes(mut self, collapse: bool) -> Self {
        self.set_collapse_duplicate_slashes(collapse);
        self
    }

    /// Configures trailing-slash normalization (`Keep`, `Strip`, or `Enforce`) and its [`RewriteAction`].
    ///
    /// # Arguments
    ///
    /// - `TrailingSlashMode` - Desired trailing-slash policy.
    /// - `RewriteAction` - Whether normalization rewrites internally or redirects.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_trailing_slash(mut self, mode: TrailingSlashMode, action: RewriteAction) -> Self {
        self.set_trailing_slash(mode)
            .set_normalization_action(action);
        self
    }

    /// Adds an `O(1)` exact-path internal rewrite rule (`from` -> `to`).
    ///
    /// # Arguments
    ///
    /// - `F` - Exact incoming path.
    /// - `T` - Rewritten internal path.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exact_rewrite<F, T>(mut self, from: F, to: T) -> Self
    where
        F: Into<String>,
        T: Into<String>,
    {
        self.get_mut_exact_rules().push(ExactRewriteRule {
            from: from.into(),
            to: to.into(),
            action: RewriteAction::InternalRewrite,
            preserve_query: true,
        });
        self
    }

    /// Adds an `O(1)` exact-path short-circuit HTTP redirect rule (`from` -> `to`).
    ///
    /// # Arguments
    ///
    /// - `F` - Exact incoming path.
    /// - `T` - Redirect destination path or URL.
    /// - `RedirectStatus` - Redirect HTTP status code.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exact_redirect<F, T>(mut self, from: F, to: T, status: RedirectStatus) -> Self
    where
        F: Into<String>,
        T: Into<String>,
    {
        self.get_mut_exact_rules().push(ExactRewriteRule {
            from: from.into(),
            to: to.into(),
            action: RewriteAction::Redirect(status),
            preserve_query: true,
        });
        self
    }

    /// Adds a segment-bounded prefix strip rule (for example `"/api/v1"` strips `"/api/v1"` internally).
    ///
    /// # Arguments
    ///
    /// - `F` - Incoming path prefix to strip.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_strip_prefix<F>(mut self, from: F) -> Self
    where
        F: Into<String>,
    {
        self.get_mut_prefix_rules().push(PrefixRewriteRule {
            from: from.into(),
            to: String::new(),
            action: RewriteAction::InternalRewrite,
            preserve_query: true,
        });
        self
    }

    /// Adds a segment-bounded prefix rewrite or redirect rule (`from` -> `to`).
    ///
    /// # Arguments
    ///
    /// - `F` - Incoming path prefix.
    /// - `T` - Replacement prefix.
    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_prefix_rule<F, T>(mut self, from: F, to: T, action: RewriteAction) -> Self
    where
        F: Into<String>,
        T: Into<String>,
    {
        self.get_mut_prefix_rules().push(PrefixRewriteRule {
            from: from.into(),
            to: to.into(),
            action,
            preserve_query: true,
        });
        self
    }

    /// Adds a regular-expression rewrite or redirect rule supporting capture replacements (`$1`, `$2`).
    ///
    /// # Arguments
    ///
    /// - `P` - Regular expression pattern.
    /// - `R` - Replacement template.
    /// - `RewriteAction` - Internal rewrite or HTTP redirect.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_regex_rule<P, R>(
        mut self,
        pattern: P,
        replacement: R,
        action: RewriteAction,
    ) -> Self
    where
        P: Into<String>,
        R: Into<String>,
    {
        self.get_mut_regex_rules().push(RegexRewriteRule {
            pattern: pattern.into(),
            replacement: replacement.into(),
            action,
            preserve_query: true,
        });
        self
    }
}

/// Inherent compilation and hot-path request evaluation for [`CompiledRewrite`].
impl CompiledRewrite {
    /// Compiles and validates `config` into `O(1)` hash tables and precompiled regex engines.
    ///
    /// # Arguments
    ///
    /// - `RewriteConfig` - Source rewrite configuration.
    ///
    /// # Returns
    ///
    /// - `Result<Self, RewriteError>` - Compiled rewrite engine or validation/regex error.
    pub fn compile(config: RewriteConfig) -> Result<Self, RewriteError> {
        let canonical_host_lower: Option<String> = match config.try_get_canonical_host() {
            Some(host) => {
                let trimmed: &str = host.trim();
                if has_unsafe_header_chars(trimmed) {
                    return Err(RewriteError::UnsafeLocation(trimmed.to_owned()));
                }
                if trimmed.is_empty() {
                    None
                } else {
                    Some(trimmed.to_ascii_lowercase())
                }
            }
            None => None,
        };
        let mut exact_map: HashMapXxHash3_64<String, CompiledExactTarget> = hash_map_xx_hash3_64();
        for rule in config.get_exact_rules() {
            if has_unsafe_header_chars(rule.get_to()) {
                return Err(RewriteError::UnsafeLocation(rule.get_to().clone()));
            }
            exact_map.insert(
                rule.get_from().clone(),
                CompiledExactTarget {
                    to: rule.get_to().clone(),
                    action: rule.get_action(),
                    preserve_query: rule.get_preserve_query(),
                },
            );
        }
        let mut prefix_rules: Vec<CompiledPrefixRule> =
            Vec::with_capacity(config.get_prefix_rules().len());
        for rule in config.get_prefix_rules() {
            if has_unsafe_header_chars(rule.get_to()) {
                return Err(RewriteError::UnsafeLocation(rule.get_to().clone()));
            }
            let norm_from: String = normalize_rule_prefix(rule.get_from());
            if norm_from.is_empty() {
                continue;
            }
            let norm_to: String = if rule.get_to().is_empty() {
                String::new()
            } else {
                normalize_rule_prefix(rule.get_to())
            };
            prefix_rules.push(CompiledPrefixRule {
                from: norm_from,
                to: norm_to,
                action: rule.get_action(),
                preserve_query: rule.get_preserve_query(),
            });
        }
        prefix_rules.sort_by_key(|rule: &CompiledPrefixRule| Reverse(rule.from.len()));
        let mut regex_rules: Vec<CompiledRegexRule> =
            Vec::with_capacity(config.get_regex_rules().len());
        for rule in config.get_regex_rules() {
            if has_unsafe_header_chars(rule.get_replacement()) {
                return Err(RewriteError::UnsafeLocation(rule.get_replacement().clone()));
            }
            let compiled_regex: Regex =
                Regex::new(rule.get_pattern()).map_err(|e: Error| RewriteError::InvalidRegex {
                    pattern: rule.get_pattern().clone(),
                    message: e.to_string(),
                })?;
            regex_rules.push(CompiledRegexRule {
                regex: compiled_regex,
                replacement: rule.get_replacement().clone(),
                action: rule.get_action(),
                preserve_query: rule.get_preserve_query(),
            });
        }
        Ok(Self {
            config,
            canonical_host_lower,
            exact_map,
            prefix_rules,
            regex_rules,
        })
    }

    /// Returns the source [`RewriteConfig`].
    ///
    /// # Returns
    ///
    /// - `&RewriteConfig` - Active configuration.
    pub fn get_config(&self) -> &RewriteConfig {
        let Self { config, .. } = self;
        config
    }

    /// Evaluates canonical host/HTTPS, path normalization, exact, prefix, and regex rules against `ctx`.
    ///
    /// On an internal rewrite, updates `ctx.get_mut_request().set_path(...)` and stores the original
    /// path under [`ATTR_ORIGINAL_PATH`]. On a redirect, populates `ctx.get_mut_response()` with the
    /// redirect status code and sanitized `Location` header.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Active Hyperlane request/response context.
    ///
    /// # Returns
    ///
    /// - `RewriteOutcome` - Whether the request was unchanged, rewritten internally, or redirected.
    pub fn apply(&self, ctx: &mut Context) -> RewriteOutcome {
        let Self {
            config,
            canonical_host_lower,
            exact_map,
            prefix_rules,
            regex_rules,
        } = self;
        if config.get_force_https() || canonical_host_lower.is_some() {
            let headers: &RequestHeaders = ctx.get_request().get_headers();
            let req_https: bool = is_request_https(headers, config.get_trust_forwarded_proto());
            let needs_https: bool = config.get_force_https() && !req_https;
            let req_host_ref: Option<&str> = find_header_back_ref(headers, HOST);
            let needs_host_redirect: bool = match (canonical_host_lower.as_deref(), req_host_ref) {
                (Some(canonical), Some(incoming)) => !host_matches_canonical(incoming, canonical),
                (Some(_), None) => true,
                (None, _) => false,
            };
            if needs_https || needs_host_redirect {
                let target_host: Option<&str> = canonical_host_lower.as_deref().or(req_host_ref);
                if let Some(host) = target_host
                    && !host.is_empty()
                    && !has_unsafe_header_chars(host)
                {
                    let scheme: &str = if config.get_force_https() || req_https {
                        SCHEME_HTTPS
                    } else {
                        SCHEME_HTTP
                    };
                    let raw_path: &str = ctx.get_request().get_path();
                    let query: Option<String> = extract_query_string(ctx);
                    let mut location: String = String::with_capacity(
                        scheme.len() + SCHEME_SEPARATOR.len() + host.len() + raw_path.len() + 16,
                    );
                    location.push_str(scheme);
                    location.push_str(SCHEME_SEPARATOR);
                    location.push_str(host);
                    location.push_str(raw_path);
                    let final_loc: String =
                        append_query_if_needed(location, query.as_deref(), true);
                    let status_code: usize = config.get_canonical_redirect_status().code();
                    let resp: &mut Response = ctx.get_mut_response();
                    resp.set_status_code(status_code)
                        .set_header(LOCATION, &final_loc)
                        .set_body(Vec::new());
                    return RewriteOutcome::Redirected {
                        status_code,
                        location: final_loc,
                    };
                }
            }
        }
        let original_path: &str = ctx.get_request().get_path();
        let after_slash: Cow<'_, str> = if config.get_collapse_duplicate_slashes() {
            collapse_slashes(original_path)
        } else {
            Cow::Borrowed(original_path)
        };
        let normalized_path: Cow<'_, str> =
            match normalize_trailing_slash(after_slash.as_ref(), config.get_trailing_slash()) {
                Cow::Borrowed(_) => after_slash,
                Cow::Owned(s) => Cow::Owned(s),
            };
        let normalized_changed: bool = matches!(normalized_path, Cow::Owned(_));
        if normalized_changed
            && let RewriteAction::Redirect(status) = config.get_normalization_action()
        {
            let target: String = normalized_path.into_owned();
            if !has_unsafe_header_chars(&target) {
                let query: Option<String> = extract_query_string(ctx);
                let location: String = append_query_if_needed(target, query.as_deref(), true);
                let status_code: usize = status.code();
                ctx.get_mut_response()
                    .set_status_code(status_code)
                    .set_header(LOCATION, &location)
                    .set_body(Vec::new());
                return RewriteOutcome::Redirected {
                    status_code,
                    location,
                };
            }
            return RewriteOutcome::Unchanged;
        }
        let working_path: &str = normalized_path.as_ref();
        let matched: Option<(String, RewriteAction, bool)> = if !exact_map.is_empty()
            && let Some(hit) = exact_map.get(working_path)
        {
            Some((hit.to.clone(), hit.action, hit.preserve_query))
        } else {
            let mut found: Option<(String, RewriteAction, bool)> = None;
            for rule in prefix_rules {
                if let Some(rest) = strip_prefix_segment(working_path, &rule.from) {
                    let replaced: String = join_prefix_replacement(&rule.to, rest);
                    found = Some((replaced, rule.action, rule.preserve_query));
                    break;
                }
            }
            if found.is_none() {
                for rule in regex_rules {
                    if let Cow::Owned(replaced) =
                        rule.regex.replace(working_path, rule.replacement.as_str())
                    {
                        found = Some((replaced, rule.action, rule.preserve_query));
                        break;
                    }
                }
            }
            found
        };
        if let Some((target, action, preserve_query)) = matched {
            match action {
                RewriteAction::Redirect(status) => {
                    if has_unsafe_header_chars(&target) {
                        return RewriteOutcome::Unchanged;
                    }
                    let query: Option<String> = extract_query_string(ctx);
                    let location: String =
                        append_query_if_needed(target, query.as_deref(), preserve_query);
                    let status_code: usize = status.code();
                    ctx.get_mut_response()
                        .set_status_code(status_code)
                        .set_header(LOCATION, &location)
                        .set_body(Vec::new());
                    return RewriteOutcome::Redirected {
                        status_code,
                        location,
                    };
                }
                RewriteAction::InternalRewrite => {
                    let prev: String = original_path.to_owned();
                    ctx.set_attribute(ATTR_ORIGINAL_PATH, prev);
                    ctx.get_mut_request().set_path(target.clone());
                    return RewriteOutcome::Rewritten(target);
                }
            }
        }
        if normalized_changed {
            let new_path: String = normalized_path.into_owned();
            let prev: String = original_path.to_owned();
            ctx.set_attribute(ATTR_ORIGINAL_PATH, prev);
            ctx.get_mut_request().set_path(new_path.clone());
            return RewriteOutcome::Rewritten(new_path);
        }
        RewriteOutcome::Unchanged
    }
}

/// Process-wide singleton management for [`RewritePlugin`].
impl RewritePlugin {
    /// Compiles `config` and initializes the global [`RewritePlugin`] once.
    ///
    /// # Arguments
    ///
    /// - `RewriteConfig` - Rewrite and redirect configuration.
    ///
    /// # Returns
    ///
    /// - `Result<&'static Self, RewriteError>` - Reference to the initialized global plugin or compilation error.
    pub fn init(config: RewriteConfig) -> Result<&'static Self, RewriteError> {
        let compiled: CompiledRewrite = CompiledRewrite::compile(config)?;
        Ok(REWRITE_PLUGIN.get_or_init(|| Self { compiled }))
    }

    /// Returns the initialized global [`RewritePlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline]
    pub fn get() -> Option<&'static Self> {
        REWRITE_PLUGIN.get()
    }

    /// Returns the compiled [`CompiledRewrite`] engine.
    ///
    /// # Returns
    ///
    /// - `&CompiledRewrite` - Precompiled rewrite engine.
    #[inline]
    pub fn get_compiled(&self) -> &CompiledRewrite {
        let Self { compiled } = self;
        compiled
    }
}

/// Implements [`ServerHook`] for [`RewriteHook`].
impl ServerHook for RewriteHook {
    /// Constructs a per-request [`RewriteHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Applies rewrite/redirect rules, short-circuiting on HTTP redirects or continuing on rewrites.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` after sending redirect bytes; `Status::Continue` otherwise.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = RewritePlugin::get() else {
            return Status::Continue;
        };
        if matches!(
            plugin.get_compiled().apply(ctx),
            RewriteOutcome::Redirected { .. }
        ) {
            let wire: ResponseData = ctx.get_mut_response().build();
            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
            return Status::Reject;
        }
        Status::Continue
    }
}