hyperlane-plugin-tenant 23.3.0

A zero-allocation multi-tenant resolution and isolation plugin for the Hyperlane framework supporting X-Tenant-Id header, Host subdomain, and path-prefix extraction, XxHash3_64 tenant registry, pluggable TenantResolver, and prebuilt 400/403/404 wire responses.
Documentation
use super::*;

/// Validates that a tenant identifier is non-empty, `<= MAX_TENANT_ID_LEN`, and `[a-zA-Z0-9_-]`.
///
/// # Arguments
///
/// - `&str` - Candidate tenant ID.
///
/// # Returns
///
/// - `bool` - `true` when syntactically valid.
#[inline]
pub fn is_valid_tenant_id(id: &str) -> bool {
    let bytes: &[u8] = id.as_bytes();
    if bytes.is_empty() || bytes.len() > MAX_TENANT_ID_LEN {
        return false;
    }
    bytes
        .iter()
        .all(|b: &u8| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
}

/// Normalizes a path prefix by ensuring a leading `/` and trimming trailing `/`.
///
/// # Arguments
///
/// - `&str` - Raw path prefix.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(raw: &str) -> String {
    let trimmed: &str = raw.trim().trim_end_matches('/');
    if trimmed.is_empty() || trimmed == ROOT_SLASH {
        return ROOT_SLASH.to_owned();
    }
    if trimmed.starts_with('/') {
        trimmed.to_owned()
    } else {
        format!("/{trimmed}")
    }
}

/// Reports whether `path` matches `prefix` on a segment boundary.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized path prefix.
///
/// # Returns
///
/// - `bool` - `true` when matched.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == ROOT_SLASH {
        return true;
    }
    if let Some(rest) = path.strip_prefix(prefix) {
        rest.is_empty() || rest.starts_with('/')
    } else {
        false
    }
}

/// Extracts the leading subdomain label from a `Host` header given a lowercased `.base_domain` suffix.
///
/// # Arguments
///
/// - `&'a str` - Raw `Host` header value (optionally including `:port`).
/// - `&str` - Lowercased suffix beginning with `.` (for example `".example.com"`).
///
/// # Returns
///
/// - `Option<&'a str>` - Extracted subdomain label when valid.
#[inline]
pub(crate) fn extract_subdomain<'a>(host: &'a str, dot_base_domain: &str) -> Option<&'a str> {
    let host_no_port: &'a str = match host.trim().split_once(':') {
        Some((h, _)) => h,
        None => host.trim(),
    };
    if host_no_port.len() <= dot_base_domain.len() {
        return None;
    }
    let split_idx: usize = host_no_port.len() - dot_base_domain.len();
    if !host_no_port.as_bytes()[split_idx..].eq_ignore_ascii_case(dot_base_domain.as_bytes()) {
        return None;
    }
    let sub: &'a str = &host_no_port[..split_idx];
    if sub.contains('.') || !is_valid_tenant_id(sub) {
        None
    } else {
        Some(sub)
    }
}

/// Extracts the tenant segment immediately following `path_prefix` (for example `"/t/acme/orders"` -> `"acme"`).
///
/// # Arguments
///
/// - `&'a str` - Request path.
/// - `&str` - Normalized prefix (for example `"/t"`).
///
/// # Returns
///
/// - `Option<&'a str>` - Extracted tenant ID slice, if valid.
#[inline]
pub(crate) fn extract_path_tenant<'a>(path: &'a str, path_prefix: &str) -> Option<&'a str> {
    let rest: &'a str = path.strip_prefix(path_prefix)?;
    let after_slash: &'a str = rest.strip_prefix('/')?;
    let segment: &'a str = match after_slash.split_once('/') {
        Some((seg, _)) => seg,
        None => after_slash,
    };
    if is_valid_tenant_id(segment) {
        Some(segment)
    } else {
        None
    }
}

/// Builds a pre-serialized HTTP wire error response.
///
/// # Arguments
///
/// - `HttpStatus` - HTTP status code.
/// - `&[u8]` - JSON error body.
///
/// # Returns
///
/// - `Vec<u8>` - Complete HTTP/1.1 wire response bytes.
pub(crate) fn build_error_wire(status: HttpStatus, body: &[u8]) -> Vec<u8> {
    let mut resp: Response = Response::default();
    resp.set_status_code(status.code())
        .set_header(CONTENT_TYPE, DEFAULT_TENANT_ERROR_CONTENT_TYPE)
        .set_body(body);
    resp.build()
}