kz-server 0.3.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use crate::error::{Result, ServerError};
use axum::http::HeaderMap;

pub const DEFAULT_CREDENTIAL_LOCATION: &str = "header:Authorization:Bearer";

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"];

pub struct CredentialLocation<'a> {
    pub header_name: &'a str,
    pub prefix: &'a str,
}

pub fn extract_bearer_token(headers: &HeaderMap) -> Option<String> {
    headers
        .get("authorization")?
        .to_str()
        .ok()?
        .strip_prefix("Bearer ")
        .filter(|t| !t.is_empty())
        .map(String::from)
}

pub fn effective_location(location: Option<&str>) -> &str {
    location.unwrap_or(DEFAULT_CREDENTIAL_LOCATION)
}

pub fn parse_credential_location(location: &str) -> std::result::Result<CredentialLocation<'_>, String> {
    let parts: Vec<&str> = location.splitn(3, ':').collect();
    if parts.len() < 2 || parts[0] != "header" {
        return Err(format!("invalid credential_location format: {location}"));
    }
    Ok(CredentialLocation {
        header_name: parts[1],
        prefix: if parts.len() == 3 { parts[2] } else { "" },
    })
}

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)
    }
}

pub fn is_blocked_host(host: &str) -> bool {
    // Strip brackets for IPv6 literals like [::1]
    let unbracketed = host.trim_start_matches('[').trim_end_matches(']');
    // For IPv6 addresses (contain ':'), don't split on ':' to strip port
    let clean = if unbracketed.contains(':') {
        unbracketed
    } else {
        // For IPv4/hostname with optional port, take only the host part
        unbracketed.split(':').next().unwrap_or(unbracketed)
    };
    if BLOCKED_HOSTS.contains(&clean) {
        return true;
    }
    if BLOCKED_SUFFIXES.iter().any(|s| clean.ends_with(s)) {
        return true;
    }
    is_private_ip(clean)
}

pub fn validate_ref(ref_path: &str) -> Result<()> {
    if ref_path.is_empty() {
        return Err(ServerError::PathTraversal("empty ref".into()));
    }
    if ref_path.contains('%') {
        return Err(ServerError::PathTraversal("encoded characters not allowed".into()));
    }
    if ref_path.contains('\0') {
        return Err(ServerError::PathTraversal("null bytes not allowed".into()));
    }
    if ref_path.split('/').any(|seg| seg == "..") {
        return Err(ServerError::PathTraversal(ref_path.into()));
    }
    Ok(())
}

fn is_private_ipv4(addr: std::net::Ipv4Addr) -> bool {
    let o = addr.octets();
    o[0] == 10
        || (o[0] == 172 && (16..=31).contains(&o[1]))
        || (o[0] == 192 && o[1] == 168)
        || o[0] == 127
        || (o[0] == 169 && o[1] == 254)
}

fn is_private_ipv6(addr: std::net::Ipv6Addr) -> bool {
    // Check IPv4-mapped addresses
    if let Some(v4) = addr.to_ipv4_mapped() {
        return is_private_ipv4(v4);
    }
    let s = addr.segments();
    s[0] == 0xfd00 || s[0] == 0xfe80 || addr == std::net::Ipv6Addr::LOCALHOST
}

/// Detect non-standard IP representations that bypass std::net parsing
fn looks_like_ip_bypass(host: &str) -> bool {
    // Pure decimal IP (e.g., 2130706433 = 127.0.0.1)
    if host.chars().all(|c| c.is_ascii_digit()) && host.parse::<u64>().is_ok() {
        return true;
    }
    // Hex IP (0x7f000001 or 0x7f.0.0.1)
    if host.starts_with("0x") || host.starts_with("0X") {
        return true;
    }
    // Octal octets (leading zero in any segment: 0177.0.0.1)
    if host.contains('.') {
        let segments: Vec<&str> = host.split('.').collect();
        if segments.len() == 4 && segments.iter().all(|s| s.chars().all(|c| c.is_ascii_digit())) {
            if segments.iter().any(|s| s.len() > 1 && s.starts_with('0')) {
                return true;
            }
        }
    }
    false
}

fn is_private_ip(host: &str) -> bool {
    // Standard IPv4
    if let Ok(addr) = host.parse::<std::net::Ipv4Addr>() {
        return is_private_ipv4(addr);
    }
    // Standard IPv6
    if let Ok(addr) = host.parse::<std::net::Ipv6Addr>() {
        return is_private_ipv6(addr);
    }
    // Reject suspicious IP formats that could bypass parsing
    // (octal: 0177.0.0.1, hex: 0x7f.0.0.1, decimal: 2130706433)
    if looks_like_ip_bypass(host) {
        return true;
    }
    false
}