agix-base 0.5.0

Agix — foundation types, traits, and context
Documentation
//! A URL written one way, as permission rules and the MCP policy read it
//! ([`NormalizedUrl`]): userinfo, query and fragment dropped, host lowercased
//! without a trailing `.`, the scheme's default port left out, `ws` / `wss`
//! read as `http` / `https`, a path's escapes of unreserved characters
//! decoded. Pattern matching over it lives in `permissions::url_rule`.
//!
//! `web.allowed_domains` is not a rule of this kind: it lists domains and the
//! network layer enforces it on hosts (`interface::exec::domains_name_host`).
//! Its callers use [`NormalizedUrl`] to get at the host.

/// A URL as rules see it: `scheme://host[:port]path`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalizedUrl {
    scheme: String,
    host: String,
    port: Option<u16>,
    path: String,
}

impl NormalizedUrl {
    /// `None` when `raw` is not an absolute URL with a host.
    pub fn parse(raw: &str) -> Option<Self> {
        let url = url::Url::parse(raw.trim()).ok()?;
        let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
        if host.is_empty() {
            return None;
        }
        let scheme = websocket_as_http(url.scheme()).to_string();
        let port = url
            .port_or_known_default()
            .filter(|p| Some(*p) != default_port(&scheme));
        Some(Self {
            scheme,
            host,
            port,
            path: normalize_escapes(url.path()),
        })
    }

    pub fn scheme(&self) -> &str {
        &self.scheme
    }

    pub fn host(&self) -> &str {
        &self.host
    }

    pub fn port(&self) -> Option<u16> {
        self.port
    }

    /// The same URL with any trailing `/` taken off its path, the form an
    /// OAuth issuer is compared in.
    pub fn without_trailing_slash(mut self) -> Self {
        let trimmed = self.path.trim_end_matches('/').len();
        self.path.truncate(trimmed);
        self
    }

    pub fn path_or_root(&self) -> &str {
        if self.path.is_empty() {
            "/"
        } else {
            &self.path
        }
    }
}

impl std::fmt::Display for NormalizedUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}://{}", self.scheme, self.host)?;
        if let Some(port) = self.port {
            write!(f, ":{port}")?;
        }
        f.write_str(&self.path)
    }
}

/// Percent-escapes of unreserved characters (letters, digits, `-`, `.`, `_`,
/// `~`) decoded, every other escape kept with upper-case hex.
pub fn normalize_escapes(path: &str) -> String {
    let mut out = String::with_capacity(path.len());
    let mut rest = path;
    while let Some(c) = rest.chars().next() {
        let escaped = rest
            .strip_prefix('%')
            .and_then(|r| r.get(..2))
            .filter(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit()))
            .and_then(|hex| u8::from_str_radix(hex, 16).ok());
        match escaped {
            Some(b) if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') => {
                out.push(b as char);
                rest = &rest[3..];
            }
            Some(b) => {
                out.push_str(&format!("%{b:02X}"));
                rest = &rest[3..];
            }
            None => {
                out.push(c);
                rest = &rest[c.len_utf8()..];
            }
        }
    }
    out
}

pub fn websocket_as_http(scheme: &str) -> &str {
    match scheme {
        "ws" => "http",
        "wss" => "https",
        other => other,
    }
}

pub fn default_port(scheme: &str) -> Option<u16> {
    match scheme {
        "http" => Some(80),
        "https" => Some(443),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_normalized_url_is_written_one_way() {
        let u = NormalizedUrl::parse("WSS://User@Corp.Example.:443/a/?q#f").unwrap();
        assert_eq!(u.to_string(), "https://corp.example/a/");
        assert_eq!(
            u.without_trailing_slash().to_string(),
            "https://corp.example/a"
        );
        assert_eq!(
            NormalizedUrl::parse("http://h.example:8080")
                .unwrap()
                .to_string(),
            "http://h.example:8080/"
        );
    }
}