merry_runtime/
network_policy.rs1use crate::{ProcessSessionPermissionSnapshot, ProcessSessionPermissionView};
9use merry_core::CapabilityPolicy;
10use std::{collections::BTreeSet, net::IpAddr};
11
12const MAX_DOMAIN_HOST_BYTES: usize = 253;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum NetworkAccessDecision {
17 Allow,
19 RequireReview,
21 Deny,
24}
25
26#[must_use]
33pub fn normalize_network_domain(raw: &str) -> Option<String> {
34 let trimmed = raw.trim();
35 if trimmed.is_empty() || trimmed.len() > MAX_DOMAIN_HOST_BYTES {
36 return None;
37 }
38 let unbracketed = trimmed
39 .strip_prefix('[')
40 .and_then(|rest| rest.strip_suffix(']'))
41 .unwrap_or(trimmed);
42 let without_trailing_dot = unbracketed.trim_end_matches('.');
43 if without_trailing_dot.is_empty() || without_trailing_dot.len() > MAX_DOMAIN_HOST_BYTES {
44 return None;
45 }
46 if without_trailing_dot.chars().any(|ch| {
47 ch.is_whitespace() || ch.is_control() || matches!(ch, '/' | '\\' | '?' | '#' | '@')
48 }) {
49 return None;
50 }
51 if let Ok(ip) = without_trailing_dot.parse::<IpAddr>() {
52 return Some(ip.to_string());
53 }
54 if without_trailing_dot.contains(':') {
56 return None;
57 }
58 if without_trailing_dot.starts_with('.') || without_trailing_dot.contains("..") {
59 return None;
60 }
61 Some(without_trailing_dot.to_ascii_lowercase())
62}
63
64#[must_use]
70pub fn is_explicit_local_network_host(host: &str) -> bool {
71 let Some(normalized) = normalize_network_domain(host) else {
72 return false;
73 };
74 if normalized == "localhost" {
75 return true;
76 }
77 normalized.parse::<IpAddr>().is_ok_and(|ip| match ip {
78 IpAddr::V4(v4) => v4.is_loopback(),
79 IpAddr::V6(v6) => v6
80 .to_ipv4_mapped()
81 .map_or_else(|| v6.is_loopback(), |mapped| mapped.is_loopback()),
82 })
83}
84
85#[derive(Debug, Clone)]
87pub struct NetworkAccessPolicy {
88 network_policy: CapabilityPolicy,
89 allow_local: bool,
90 allowed_domains: BTreeSet<String>,
91 session_permissions: Option<ProcessSessionPermissionView>,
92}
93
94impl Default for NetworkAccessPolicy {
95 fn default() -> Self {
96 Self::new(CapabilityPolicy::Ask, true)
97 }
98}
99
100impl NetworkAccessPolicy {
101 #[must_use]
104 pub fn new(network_policy: CapabilityPolicy, allow_local: bool) -> Self {
105 Self {
106 network_policy,
107 allow_local,
108 allowed_domains: BTreeSet::new(),
109 session_permissions: None,
110 }
111 }
112
113 #[must_use]
116 pub fn with_allowed_domains<I, S>(mut self, domains: I) -> Self
117 where
118 I: IntoIterator<Item = S>,
119 S: AsRef<str>,
120 {
121 self.allowed_domains = domains
122 .into_iter()
123 .filter_map(|domain| normalize_network_domain(domain.as_ref()))
124 .collect();
125 self
126 }
127
128 #[must_use]
132 pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
133 self.session_permissions = Some(view);
134 self
135 }
136
137 #[must_use]
138 pub(crate) fn session_permissions_view(&self) -> Option<ProcessSessionPermissionView> {
139 self.session_permissions.clone()
140 }
141
142 #[must_use]
144 pub const fn network_policy(&self) -> CapabilityPolicy {
145 self.network_policy
146 }
147
148 #[must_use]
151 pub const fn allow_local(&self) -> bool {
152 self.allow_local
153 }
154
155 #[must_use]
157 pub const fn evaluate_data_url(&self) -> NetworkAccessDecision {
158 if self.allow_local {
159 NetworkAccessDecision::Allow
160 } else {
161 NetworkAccessDecision::Deny
162 }
163 }
164
165 #[must_use]
169 pub fn evaluate_host(&self, host: &str, once_domains: &[String]) -> NetworkAccessDecision {
170 let session = self
171 .session_permissions
172 .as_ref()
173 .and_then(|view| view.snapshot().ok());
174 self.evaluate_host_with_session(host, session.as_ref(), once_domains)
175 }
176
177 #[must_use]
181 pub fn evaluate_host_with_session(
182 &self,
183 host: &str,
184 session: Option<&ProcessSessionPermissionSnapshot>,
185 once_domains: &[String],
186 ) -> NetworkAccessDecision {
187 let Some(normalized) = normalize_network_domain(host) else {
188 return NetworkAccessDecision::Deny;
189 };
190 if is_explicit_local_network_host(&normalized) {
191 return if self.allow_local {
192 NetworkAccessDecision::Allow
193 } else {
194 NetworkAccessDecision::Deny
195 };
196 }
197 match self.network_policy {
198 CapabilityPolicy::Deny => NetworkAccessDecision::Deny,
199 CapabilityPolicy::Allow => NetworkAccessDecision::Allow,
200 CapabilityPolicy::Ask => {
201 if once_domains.iter().any(|candidate| {
202 normalize_network_domain(candidate).as_deref() == Some(normalized.as_str())
203 }) {
204 return NetworkAccessDecision::Allow;
205 }
206 if self.allowed_domains.contains(&normalized) {
207 return NetworkAccessDecision::Allow;
208 }
209 if let Some(snapshot) = session
210 && (snapshot.network_allowed() || snapshot.allows_domain(&normalized))
211 {
212 return NetworkAccessDecision::Allow;
213 }
214 NetworkAccessDecision::RequireReview
215 }
216 }
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223 use crate::ProcessSessionPermissions;
224
225 #[test]
226 fn normalize_network_domain_canonicalizes_hosts_and_rejects_malformed_inputs() {
227 assert_eq!(
228 normalize_network_domain(" Docs.RS. "),
229 Some("docs.rs".to_owned())
230 );
231 assert_eq!(normalize_network_domain("[::1]"), Some("::1".to_owned()));
232 assert_eq!(
233 normalize_network_domain("127.0.0.1"),
234 Some("127.0.0.1".to_owned())
235 );
236 assert_eq!(normalize_network_domain(""), None);
237 assert_eq!(normalize_network_domain("docs.rs:443"), None);
238 assert_eq!(normalize_network_domain("https://docs.rs"), None);
239 assert_eq!(normalize_network_domain("docs.rs/path"), None);
240 assert_eq!(normalize_network_domain("bad host"), None);
241 assert_eq!(normalize_network_domain("a..b.com"), None);
242 }
243
244 #[test]
245 fn deny_policy_hard_blocks_external_domains_even_when_saved_or_session_granted() {
246 let session = ProcessSessionPermissions::new();
247 session
248 .retain_domain_grants(["docs.rs".to_owned()])
249 .expect("retain domain");
250 let policy = NetworkAccessPolicy::new(CapabilityPolicy::Deny, true)
251 .with_allowed_domains(["docs.rs"])
252 .with_session_permissions(session.view());
253
254 assert_eq!(
255 policy.evaluate_host("docs.rs", &["docs.rs".to_owned()]),
256 NetworkAccessDecision::Deny
257 );
258 assert_eq!(
259 policy.evaluate_host("localhost", &[]),
260 NetworkAccessDecision::Allow,
261 "browser.allow_local stays independent for explicit loopback debugging"
262 );
263 assert_eq!(policy.evaluate_data_url(), NetworkAccessDecision::Allow);
264 }
265
266 #[test]
267 fn allow_local_false_blocks_loopback_and_data_urls() {
268 let policy = NetworkAccessPolicy::new(CapabilityPolicy::Allow, false);
269 assert_eq!(
270 policy.evaluate_host("localhost", &[]),
271 NetworkAccessDecision::Deny
272 );
273 assert_eq!(
274 policy.evaluate_host("127.0.0.1", &[]),
275 NetworkAccessDecision::Deny
276 );
277 assert_eq!(
278 policy.evaluate_host("::1", &[]),
279 NetworkAccessDecision::Deny
280 );
281 assert_eq!(policy.evaluate_data_url(), NetworkAccessDecision::Deny);
282 assert_eq!(
283 policy.evaluate_host("docs.rs", &[]),
284 NetworkAccessDecision::Allow
285 );
286 }
287
288 #[test]
289 fn ask_policy_enforces_exact_hostname_matching_and_live_session_revocation() {
290 let session = ProcessSessionPermissions::new();
291 let policy = NetworkAccessPolicy::new(CapabilityPolicy::Ask, true)
292 .with_allowed_domains(["crates.io"])
293 .with_session_permissions(session.view());
294
295 assert_eq!(
296 policy.evaluate_host("crates.io", &[]),
297 NetworkAccessDecision::Allow
298 );
299 assert_eq!(
300 policy.evaluate_host("api.crates.io", &[]),
301 NetworkAccessDecision::RequireReview,
302 "workspace allowed_domains must match exact hostname only"
303 );
304 assert_eq!(
305 policy.evaluate_host("docs.rs", &[]),
306 NetworkAccessDecision::RequireReview
307 );
308 assert_eq!(
309 policy.evaluate_host("docs.rs", &["DOCS.RS.".to_owned()]),
310 NetworkAccessDecision::Allow
311 );
312
313 session
314 .retain_domain_grants(["docs.rs".to_owned()])
315 .expect("retain domain");
316 assert_eq!(
317 policy.evaluate_host("docs.rs", &[]),
318 NetworkAccessDecision::Allow
319 );
320 assert_eq!(
321 policy.evaluate_host("evil.docs.rs", &[]),
322 NetworkAccessDecision::RequireReview,
323 "session domain grant must match exact hostname only"
324 );
325
326 let grants = session.grants().expect("grants");
327 assert_eq!(grants.len(), 1);
328 assert!(session.revoke(grants[0].id()).expect("revoke"));
329 assert_eq!(
330 policy.evaluate_host("docs.rs", &[]),
331 NetworkAccessDecision::RequireReview,
332 "revoking session domain grant must immediately require review again"
333 );
334 }
335}