kz-server 0.2.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
//! HTTP request security utilities — credential handling and SSRF protection.

use axum::http::HeaderMap;

// ---------------------------------------------------------------------------
// Credential handling
// ---------------------------------------------------------------------------

/// Default credential location: inject as Bearer token in Authorization header.
pub const DEFAULT_CREDENTIAL_LOCATION: &str = "header:Authorization:Bearer";

/// Extract a Bearer token from the Authorization header.
pub(crate) fn extract_bearer_token(headers: &HeaderMap) -> Option<String> {
    let auth_header = headers.get(axum::http::header::AUTHORIZATION)?.to_str().ok()?;
    let token = auth_header.strip_prefix("Bearer ")?;
    if token.is_empty() {
        return None;
    }
    Some(token.to_string())
}

/// Return the effective credential location, falling back to the default.
pub(crate) fn effective_location(location: Option<&str>) -> &str {
    location.unwrap_or(DEFAULT_CREDENTIAL_LOCATION)
}

/// Parsed credential location for injecting secrets into HTTP requests.
pub struct CredentialLocation<'a> {
    pub header_name: &'a str,
    pub prefix: &'a str,
}

/// Parse a credential_location string like "header:Authorization:Bearer".
/// Returns the header name and prefix, or an error description.
pub fn parse_credential_location(location: &str) -> Result<CredentialLocation<'_>, String> {
    let parts: Vec<&str> = location.splitn(3, ':').collect();
    match parts.as_slice() {
        ["header", header_name, prefix] => Ok(CredentialLocation {
            header_name,
            prefix,
        }),
        _ => Err(format!(
            "unsupported credential_location format: '{location}'. Expected 'header:<name>:<prefix>'"
        )),
    }
}

/// Format a secret value with the credential location prefix.
pub fn format_credential_value(loc: &CredentialLocation<'_>, secret_value: &str) -> String {
    if loc.prefix.is_empty() {
        secret_value.to_string()
    } else {
        format!("{} {secret_value}", loc.prefix)
    }
}

// ---------------------------------------------------------------------------
// SSRF protection
// ---------------------------------------------------------------------------

const BLOCKED_HOSTS: &[&str] = &[
    "localhost",
    "0.0.0.0",
    "::1",
    "169.254.169.254",
    "fd00:ec2::254",
    "metadata.google.internal",
    "metadata.goog",
    "metadata",
    "100.100.100.200",
];

const BLOCKED_SUFFIXES: &[&str] = &[".internal", ".local"];

/// Unified SSRF protection: check if a host refers to a private, internal, or
/// cloud-metadata address that should be blocked.
///
/// Covers:
/// - Loopback, private, and link-local IPv4/IPv6 addresses
/// - Well-known cloud metadata endpoints (AWS, GCP, Azure, Alibaba)
/// - `.internal` and `.local` domain suffixes
pub(crate) fn is_blocked_host(host: &str) -> bool {
    let host = host.split(':').next().unwrap_or(host);

    // Explicit hostname checks
    if BLOCKED_HOSTS.contains(&host) {
        return true;
    }

    // Domain suffix checks
    if BLOCKED_SUFFIXES.iter().any(|suffix| host.ends_with(suffix)) {
        return true;
    }

    // IP address checks (covers IPv4, IPv6, and IPv4-mapped IPv6)
    if let Ok(ip) = host.trim_matches(|c| c == '[' || c == ']').parse::<std::net::IpAddr>() {
        return match ip {
            std::net::IpAddr::V4(v4) => {
                v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified()
            }
            std::net::IpAddr::V6(v6) => {
                if v6.is_loopback() || v6.is_unspecified() {
                    return true;
                }
                if let Some(v4) = v6.to_ipv4_mapped() {
                    v4.is_loopback() || v4.is_private() || v4.is_link_local()
                } else {
                    false
                }
            }
        };
    }

    false
}