hyperlane-plugin-rewrite 22.14.0

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
use super::*;

/// Reports whether `value` contains forbidden HTTP header CR or LF bytes.
///
/// # Arguments
///
/// - `&str` - Candidate header or redirect target string.
///
/// # Returns
///
/// - `bool` - `true` when CR (`\r`), LF (`\n`), or NUL (`\0`) is present.
#[inline]
pub(crate) fn has_unsafe_header_chars(value: &str) -> bool {
    value
        .bytes()
        .any(|b: u8| b == b'\r' || b == b'\n' || b == b'\0')
}

/// Looks up a header value without cloning using an `O(1)` lowercase fast path.
///
/// # Arguments
///
/// - `&'a RequestHeaders` - Incoming request header map.
/// - `&str` - Canonical lowercase header name.
///
/// # Returns
///
/// - `Option<&'a str>` - Last header value slice if present.
#[inline]
pub(crate) fn find_header_back_ref<'a>(
    headers: &'a RequestHeaders,
    lower_name: &str,
) -> Option<&'a str> {
    if let Some(vals) = headers.get(lower_name) {
        return vals.back().map(String::as_str);
    }
    headers
        .iter()
        .find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
        .and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}

/// Detects whether the incoming request arrived over HTTPS using `X-Forwarded-Proto` or RFC 7239 `Forwarded`.
///
/// # Arguments
///
/// - `&RequestHeaders` - Request headers.
/// - `bool` - Whether forwarding headers are trusted.
///
/// # Returns
///
/// - `bool` - `true` when the request scheme is `https`.
#[inline]
pub(crate) fn is_request_https(headers: &RequestHeaders, trust_forwarded_proto: bool) -> bool {
    if !trust_forwarded_proto {
        return false;
    }
    if let Some(proto) = find_header_back_ref(headers, X_FORWARDED_PROTO) {
        let first: &str = proto.split(',').next().unwrap_or(proto).trim();
        return first.eq_ignore_ascii_case(SCHEME_HTTPS);
    }
    if let Some(fwd) = find_header_back_ref(headers, FORWARDED) {
        for element in fwd.split(',') {
            for param in element.split(';') {
                let trimmed: &str = param.trim();
                if trimmed.len() > FORWARDED_PROTO_PREFIX.len()
                    && trimmed[..FORWARDED_PROTO_PREFIX.len()]
                        .eq_ignore_ascii_case(FORWARDED_PROTO_PREFIX)
                {
                    let val: &str = trimmed[FORWARDED_PROTO_PREFIX.len()..]
                        .trim()
                        .trim_matches('"');
                    return val.eq_ignore_ascii_case(SCHEME_HTTPS);
                }
            }
        }
    }
    false
}

/// Compares incoming `Host` header against lowercased canonical host (ignoring default `:80`/`:443` suffix).
///
/// # Arguments
///
/// - `&str` - Incoming `Host` header value.
/// - `&str` - Lowercased canonical host.
///
/// # Returns
///
/// - `bool` - `true` when incoming host matches canonical host.
#[inline]
pub(crate) fn host_matches_canonical(raw_host: &str, canonical_lower: &str) -> bool {
    let trimmed: &str = raw_host.trim();
    if trimmed.eq_ignore_ascii_case(canonical_lower) {
        return true;
    }
    let stripped: &str = trimmed
        .strip_suffix(DEFAULT_HTTP_PORT)
        .or_else(|| trimmed.strip_suffix(DEFAULT_HTTPS_PORT))
        .unwrap_or(trimmed);
    stripped.eq_ignore_ascii_case(canonical_lower)
}

/// Collapses consecutive `'/'` bytes into a single `'/'` without allocating if none exist.
///
/// # Arguments
///
/// - `&str` - Candidate request path.
///
/// # Returns
///
/// - `Cow<'_, str>` - Borrowed path when already clean, or newly collapsed path.
#[inline]
pub(crate) fn collapse_slashes(path: &str) -> Cow<'_, str> {
    if !path.contains("//") {
        return Cow::Borrowed(path);
    }
    let mut out: String = String::with_capacity(path.len());
    let mut prev_slash: bool = false;
    for ch in path.chars() {
        if ch == '/' {
            if !prev_slash {
                out.push('/');
            }
            prev_slash = true;
        } else {
            out.push(ch);
            prev_slash = false;
        }
    }
    Cow::Owned(out)
}

/// Applies [`TrailingSlashMode`] to `path` without allocating when already normalized.
///
/// # Arguments
///
/// - `&str` - Candidate request path.
/// - `TrailingSlashMode` - Desired trailing-slash policy.
///
/// # Returns
///
/// - `Cow<'_, str>` - Borrowed path when unchanged, or normalized path.
#[inline]
pub(crate) fn normalize_trailing_slash(path: &str, mode: TrailingSlashMode) -> Cow<'_, str> {
    if path == "/" || path.is_empty() {
        return Cow::Borrowed(path);
    }
    match mode {
        TrailingSlashMode::Keep => Cow::Borrowed(path),
        TrailingSlashMode::Strip => {
            if let Some(stripped) = path.strip_suffix('/') {
                if stripped.is_empty() {
                    Cow::Borrowed("/")
                } else {
                    Cow::Owned(stripped.to_owned())
                }
            } else {
                Cow::Borrowed(path)
            }
        }
        TrailingSlashMode::Enforce => {
            if path.ends_with('/') {
                Cow::Borrowed(path)
            } else {
                let mut out: String = String::with_capacity(path.len() + 1);
                out.push_str(path);
                out.push('/');
                Cow::Owned(out)
            }
        }
    }
}

/// Normalizes a prefix rule path by trimming trailing slashes while preserving `"/"`.
///
/// # Arguments
///
/// - `&str` - Raw prefix path.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_rule_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    trimmed.trim_end_matches('/').to_owned()
}

/// Checks whether `path` matches `prefix` on a segment boundary and returns the remaining suffix.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized rule prefix.
///
/// # Returns
///
/// - `Option<&str>` - Remaining path suffix (`""` or starting with `'/'`), or `None` on mismatch.
#[inline]
pub(crate) fn strip_prefix_segment<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
    if prefix == "/" {
        return Some(path);
    }
    let rest: &'a str = path.strip_prefix(prefix)?;
    if rest.is_empty() || rest.starts_with('/') {
        Some(rest)
    } else {
        None
    }
}

/// Joins a replacement prefix `to` with the remaining segment suffix `rest`.
///
/// # Arguments
///
/// - `&str` - Replacement prefix (may be empty for pure prefix stripping).
/// - `&str` - Remaining suffix from [`strip_prefix_segment`].
///
/// # Returns
///
/// - `String` - Rewritten path starting with `'/'` (or absolute URL when `to` has a scheme).
pub(crate) fn join_prefix_replacement(to: &str, rest: &str) -> String {
    if to.is_empty() {
        if rest.is_empty() {
            return "/".to_owned();
        }
        return rest.to_owned();
    }
    let mut out: String = String::with_capacity(to.len() + rest.len());
    out.push_str(to);
    out.push_str(rest);
    out
}

/// Extracts the raw query string (without leading `'?'`) from `Context`, if any.
///
/// # Arguments
///
/// - `&Context` - Active request context.
///
/// # Returns
///
/// - `Option<String>` - Query string without leading `'?'`.
pub(crate) fn extract_query_string(ctx: &Context) -> Option<String> {
    if let Some(target) = ctx.get_request_target()
        && let Some((_, q)) = target.split_once('?')
        && !q.is_empty()
    {
        return Some(q.to_owned());
    }
    let querys: &RequestQuerys = ctx.get_request().get_querys();
    if querys.is_empty() {
        return None;
    }
    let mut out: String = String::new();
    let mut first: bool = true;
    for (k, vals) in querys {
        for v in vals {
            if !first {
                out.push('&');
            }
            first = false;
            out.push_str(k);
            if !v.is_empty() {
                out.push('=');
                out.push_str(v);
            }
        }
    }
    if out.is_empty() { None } else { Some(out) }
}

/// Appends an optional query string to `target` when `preserve_query` is enabled and `target` has no `'?'`.
///
/// # Arguments
///
/// - `String` - Base redirect location.
/// - `Option<&str>` - Original query string without `'?'`.
/// - `bool` - Whether query preservation is enabled.
///
/// # Returns
///
/// - `String` - Final `Location` header value.
pub(crate) fn append_query_if_needed(
    mut target: String,
    query: Option<&str>,
    preserve_query: bool,
) -> String {
    if preserve_query
        && !target.contains('?')
        && let Some(q) = query
        && !q.is_empty()
    {
        target.push('?');
        target.push_str(q);
    }
    target
}