hyperlane-plugin-cors 22.14.0

A zero-allocation precompiled CORS plugin for the Hyperlane framework with exact/suffix/predicate origin matching, safe credential reflection, RFC preflight handling, and Vary header merging.
Documentation
use super::*;

/// Borrows the last value of a lowercased HTTP request header without heap allocation.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercased header key name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline(always)]
pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
    req.get_headers()
        .get(lower_key)
        .and_then(|values: &RequestHeadersValue| values.back())
        .map(String::as_str)
}

/// Checks whether `haystack` ends with `suffix` using zero-allocation ASCII case-insensitive comparison.
///
/// # Arguments
///
/// - `&str` - Candidate string.
/// - `&str` - Expected suffix.
///
/// # Returns
///
/// - `bool` - `true` when `haystack` ends with `suffix` ignoring ASCII case.
#[inline(always)]
pub(crate) fn ends_with_ignore_ascii_case(haystack: &str, suffix: &str) -> bool {
    let h_len: usize = haystack.len();
    let s_len: usize = suffix.len();
    if h_len < s_len {
        return false;
    }
    haystack.as_bytes()[h_len - s_len..].eq_ignore_ascii_case(suffix.as_bytes())
}

/// Extracts the lowercased scheme+host authority or host portion of an `Origin` URL for suffix checks.
///
/// # Arguments
///
/// - `&str` - Raw incoming `Origin` header value.
///
/// # Returns
///
/// - `&str` - Host slice without scheme or port, or empty when malformed.
#[inline]
pub(crate) fn extract_origin_host(origin: &str) -> &str {
    let trimmed: &str = origin.trim();
    let without_scheme: &str = match trimmed.split_once(ORIGIN_SCHEME_SEP) {
        Some((_, rest)) => rest,
        None => return "",
    };
    let authority: &str = without_scheme.split('/').next().unwrap_or(without_scheme);
    if authority.starts_with('[') {
        match authority.find(']') {
            Some(end) => &authority[..=end],
            None => "",
        }
    } else {
        authority.split(':').next().unwrap_or(authority)
    }
}

/// Appends `token` to a response's `Vary` header if not already present (ASCII case-insensitive).
///
/// # Arguments
///
/// - `&mut Response` - Target HTTP response.
/// - `&str` - Header token to add to `Vary`.
#[inline]
pub(crate) fn merge_vary_header(response: &mut Response, token: &str) {
    if let Some(values) = response.get_mut_headers().get_mut(VARY)
        && let Some(last) = values.back_mut()
    {
        let already: bool = last
            .split(',')
            .any(|part: &str| part.trim().eq_ignore_ascii_case(token));
        if !already {
            last.reserve(COMMA_SPACE.len() + token.len());
            last.push_str(COMMA_SPACE);
            last.push_str(token);
        }
        return;
    }
    response.set_header(VARY, token);
}

/// Reports whether a request header token list contains any non-wildcard explicit header name.
///
/// # Arguments
///
/// - `&[String]` - Configured allowed headers.
///
/// # Returns
///
/// - `bool` - `true` when headers should be mirrored from `Access-Control-Request-Headers`.
pub(crate) fn should_mirror_request_headers(headers: &[String]) -> bool {
    headers.is_empty()
        || headers
            .iter()
            .any(|item: &String| item.trim() == CORS_WILDCARD)
}