use crate::{ProcessSessionPermissionSnapshot, ProcessSessionPermissionView};
use merry_core::CapabilityPolicy;
use std::{collections::BTreeSet, net::IpAddr};
const MAX_DOMAIN_HOST_BYTES: usize = 253;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkAccessDecision {
Allow,
RequireReview,
Deny,
}
#[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());
}
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())
}
#[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()),
})
}
#[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 {
#[must_use]
pub fn new(network_policy: CapabilityPolicy, allow_local: bool) -> Self {
Self {
network_policy,
allow_local,
allowed_domains: BTreeSet::new(),
session_permissions: None,
}
}
#[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
}
#[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()
}
#[must_use]
pub const fn network_policy(&self) -> CapabilityPolicy {
self.network_policy
}
#[must_use]
pub const fn allow_local(&self) -> bool {
self.allow_local
}
#[must_use]
pub const fn evaluate_data_url(&self) -> NetworkAccessDecision {
if self.allow_local {
NetworkAccessDecision::Allow
} else {
NetworkAccessDecision::Deny
}
}
#[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)
}
#[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"
);
}
}