merry-runtime 0.1.4

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
//! Unified outbound network and domain admission policy shared by in-process
//! web/browser tools (`web_fetch`, `browser_tab`, `browser_network`) and live
//! host-process backends.
//!
//! Pure Rust with zero `fork`/`exec`, so desktop CLI/TUI, Python SDK, Windows,
//! and Apple App Sandbox (`rootshell`) evaluate the exact same network policy.

use crate::{ProcessSessionPermissionSnapshot, ProcessSessionPermissionView};
use merry_core::CapabilityPolicy;
use std::{collections::BTreeSet, net::IpAddr};

const MAX_DOMAIN_HOST_BYTES: usize = 253;

/// Three-state decision produced by [`NetworkAccessPolicy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkAccessDecision {
    /// Target host or local document is authorized to proceed immediately.
    Allow,
    /// Target host requires permission admission review (AI reviewer and/or human).
    RequireReview,
    /// Target host or local document is hard-blocked by policy and must not be
    /// escalated through approval review.
    Deny,
}

/// Normalizes a hostname or IP literal for exact domain policy matching.
///
/// Strips surrounding whitespace, optional IPv6 brackets, and trailing DNS
/// root dots, then lowercases ASCII characters. Rejects empty strings, control
/// characters, whitespace, scheme/path/query/userinfo delimiters, and overly
/// long hostnames.
#[must_use]
pub fn normalize_network_domain(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() || trimmed.len() > MAX_DOMAIN_HOST_BYTES {
        return None;
    }
    let unbracketed = trimmed
        .strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .unwrap_or(trimmed);
    let without_trailing_dot = unbracketed.trim_end_matches('.');
    if without_trailing_dot.is_empty() || without_trailing_dot.len() > MAX_DOMAIN_HOST_BYTES {
        return None;
    }
    if without_trailing_dot.chars().any(|ch| {
        ch.is_whitespace() || ch.is_control() || matches!(ch, '/' | '\\' | '?' | '#' | '@')
    }) {
        return None;
    }
    if let Ok(ip) = without_trailing_dot.parse::<IpAddr>() {
        return Some(ip.to_string());
    }
    // Reject host:port or malformed colons outside IPv6 literals.
    if without_trailing_dot.contains(':') {
        return None;
    }
    if without_trailing_dot.starts_with('.') || without_trailing_dot.contains("..") {
        return None;
    }
    Some(without_trailing_dot.to_ascii_lowercase())
}

/// Returns whether `host` explicitly names a local loopback target (`localhost`,
/// `127.0.0.0/8`, `::1`, or IPv4-mapped loopback IPv6).
///
/// External hostnames never return `true`, preserving DNS-rebinding defenses
/// enforced by SSRF checks.
#[must_use]
pub fn is_explicit_local_network_host(host: &str) -> bool {
    let Some(normalized) = normalize_network_domain(host) else {
        return false;
    };
    if normalized == "localhost" {
        return true;
    }
    normalized.parse::<IpAddr>().is_ok_and(|ip| match ip {
        IpAddr::V4(v4) => v4.is_loopback(),
        IpAddr::V6(v6) => v6
            .to_ipv4_mapped()
            .map_or_else(|| v6.is_loopback(), |mapped| mapped.is_loopback()),
    })
}

/// Single-source-of-truth outbound network and domain admission policy.
#[derive(Debug, Clone)]
pub struct NetworkAccessPolicy {
    network_policy: CapabilityPolicy,
    allow_local: bool,
    allowed_domains: BTreeSet<String>,
    session_permissions: Option<ProcessSessionPermissionView>,
}

impl Default for NetworkAccessPolicy {
    fn default() -> Self {
        Self::new(CapabilityPolicy::Ask, true)
    }
}

impl NetworkAccessPolicy {
    /// Creates a network access policy from the effective three-state network
    /// capability policy and local loopback/data-document allowance.
    #[must_use]
    pub fn new(network_policy: CapabilityPolicy, allow_local: bool) -> Self {
        Self {
            network_policy,
            allow_local,
            allowed_domains: BTreeSet::new(),
            session_permissions: None,
        }
    }

    /// Installs workspace-persisted exact allowed domains (from
    /// `workspace-permissions.json`). Invalid entries are ignored safely.
    #[must_use]
    pub fn with_allowed_domains<I, S>(mut self, domains: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.allowed_domains = domains
            .into_iter()
            .filter_map(|domain| normalize_network_domain(domain.as_ref()))
            .collect();
        self
    }

    /// Attaches a live read-only view of session-approved capability grants so
    /// session domain/network grants and `/permissions` revocations take effect
    /// immediately.
    #[must_use]
    pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
        self.session_permissions = Some(view);
        self
    }

    #[must_use]
    pub(crate) fn session_permissions_view(&self) -> Option<ProcessSessionPermissionView> {
        self.session_permissions.clone()
    }

    /// Returns the effective three-state outbound network policy.
    #[must_use]
    pub const fn network_policy(&self) -> CapabilityPolicy {
        self.network_policy
    }

    /// Returns whether explicit local targets (`localhost`, `127.0.0.1`, `::1`,
    /// and `data:text/html` / `data:text/plain`) are permitted without review.
    #[must_use]
    pub const fn allow_local(&self) -> bool {
        self.allow_local
    }

    /// Evaluates access to a self-contained browser `data:` document.
    #[must_use]
    pub const fn evaluate_data_url(&self) -> NetworkAccessDecision {
        if self.allow_local {
            NetworkAccessDecision::Allow
        } else {
            NetworkAccessDecision::Deny
        }
    }

    /// Evaluates outbound HTTP(S) access to `host` against the configured
    /// `network` policy, `allow_local`, workspace `allowed_domains`, live
    /// session grants, and optional single-action `once_domains`.
    #[must_use]
    pub fn evaluate_host(&self, host: &str, once_domains: &[String]) -> NetworkAccessDecision {
        let session = self
            .session_permissions
            .as_ref()
            .and_then(|view| view.snapshot().ok());
        self.evaluate_host_with_session(host, session.as_ref(), once_domains)
    }

    /// Pure evaluation of outbound HTTP(S) access to `host` against an
    /// explicitly supplied session permission snapshot and single-action
    /// `once_domains`.
    #[must_use]
    pub fn evaluate_host_with_session(
        &self,
        host: &str,
        session: Option<&ProcessSessionPermissionSnapshot>,
        once_domains: &[String],
    ) -> NetworkAccessDecision {
        let Some(normalized) = normalize_network_domain(host) else {
            return NetworkAccessDecision::Deny;
        };
        if is_explicit_local_network_host(&normalized) {
            return if self.allow_local {
                NetworkAccessDecision::Allow
            } else {
                NetworkAccessDecision::Deny
            };
        }
        match self.network_policy {
            CapabilityPolicy::Deny => NetworkAccessDecision::Deny,
            CapabilityPolicy::Allow => NetworkAccessDecision::Allow,
            CapabilityPolicy::Ask => {
                if once_domains.iter().any(|candidate| {
                    normalize_network_domain(candidate).as_deref() == Some(normalized.as_str())
                }) {
                    return NetworkAccessDecision::Allow;
                }
                if self.allowed_domains.contains(&normalized) {
                    return NetworkAccessDecision::Allow;
                }
                if let Some(snapshot) = session
                    && (snapshot.network_allowed() || snapshot.allows_domain(&normalized))
                {
                    return NetworkAccessDecision::Allow;
                }
                NetworkAccessDecision::RequireReview
            }
        }
    }
}

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

    #[test]
    fn normalize_network_domain_canonicalizes_hosts_and_rejects_malformed_inputs() {
        assert_eq!(
            normalize_network_domain(" Docs.RS. "),
            Some("docs.rs".to_owned())
        );
        assert_eq!(normalize_network_domain("[::1]"), Some("::1".to_owned()));
        assert_eq!(
            normalize_network_domain("127.0.0.1"),
            Some("127.0.0.1".to_owned())
        );
        assert_eq!(normalize_network_domain(""), None);
        assert_eq!(normalize_network_domain("docs.rs:443"), None);
        assert_eq!(normalize_network_domain("https://docs.rs"), None);
        assert_eq!(normalize_network_domain("docs.rs/path"), None);
        assert_eq!(normalize_network_domain("bad host"), None);
        assert_eq!(normalize_network_domain("a..b.com"), None);
    }

    #[test]
    fn deny_policy_hard_blocks_external_domains_even_when_saved_or_session_granted() {
        let session = ProcessSessionPermissions::new();
        session
            .retain_domain_grants(["docs.rs".to_owned()])
            .expect("retain domain");
        let policy = NetworkAccessPolicy::new(CapabilityPolicy::Deny, true)
            .with_allowed_domains(["docs.rs"])
            .with_session_permissions(session.view());

        assert_eq!(
            policy.evaluate_host("docs.rs", &["docs.rs".to_owned()]),
            NetworkAccessDecision::Deny
        );
        assert_eq!(
            policy.evaluate_host("localhost", &[]),
            NetworkAccessDecision::Allow,
            "browser.allow_local stays independent for explicit loopback debugging"
        );
        assert_eq!(policy.evaluate_data_url(), NetworkAccessDecision::Allow);
    }

    #[test]
    fn allow_local_false_blocks_loopback_and_data_urls() {
        let policy = NetworkAccessPolicy::new(CapabilityPolicy::Allow, false);
        assert_eq!(
            policy.evaluate_host("localhost", &[]),
            NetworkAccessDecision::Deny
        );
        assert_eq!(
            policy.evaluate_host("127.0.0.1", &[]),
            NetworkAccessDecision::Deny
        );
        assert_eq!(
            policy.evaluate_host("::1", &[]),
            NetworkAccessDecision::Deny
        );
        assert_eq!(policy.evaluate_data_url(), NetworkAccessDecision::Deny);
        assert_eq!(
            policy.evaluate_host("docs.rs", &[]),
            NetworkAccessDecision::Allow
        );
    }

    #[test]
    fn ask_policy_enforces_exact_hostname_matching_and_live_session_revocation() {
        let session = ProcessSessionPermissions::new();
        let policy = NetworkAccessPolicy::new(CapabilityPolicy::Ask, true)
            .with_allowed_domains(["crates.io"])
            .with_session_permissions(session.view());

        assert_eq!(
            policy.evaluate_host("crates.io", &[]),
            NetworkAccessDecision::Allow
        );
        assert_eq!(
            policy.evaluate_host("api.crates.io", &[]),
            NetworkAccessDecision::RequireReview,
            "workspace allowed_domains must match exact hostname only"
        );
        assert_eq!(
            policy.evaluate_host("docs.rs", &[]),
            NetworkAccessDecision::RequireReview
        );
        assert_eq!(
            policy.evaluate_host("docs.rs", &["DOCS.RS.".to_owned()]),
            NetworkAccessDecision::Allow
        );

        session
            .retain_domain_grants(["docs.rs".to_owned()])
            .expect("retain domain");
        assert_eq!(
            policy.evaluate_host("docs.rs", &[]),
            NetworkAccessDecision::Allow
        );
        assert_eq!(
            policy.evaluate_host("evil.docs.rs", &[]),
            NetworkAccessDecision::RequireReview,
            "session domain grant must match exact hostname only"
        );

        let grants = session.grants().expect("grants");
        assert_eq!(grants.len(), 1);
        assert!(session.revoke(grants[0].id()).expect("revoke"));
        assert_eq!(
            policy.evaluate_host("docs.rs", &[]),
            NetworkAccessDecision::RequireReview,
            "revoking session domain grant must immediately require review again"
        );
    }
}