Skip to main content

mq_lang/io/sandboxed/
net_access.rs

1use crate::io::url_allowlist;
2
3/// Network access granted to [`SandboxedIo`](super::SandboxedIo); same shape as
4/// [`PathAccess`](super::PathAccess)/[`EnvAccess`](super::EnvAccess) but keyed by domain
5/// (e.g. `mq-run`'s `--allow-net`).
6#[derive(Debug, Clone, Default, PartialEq, Eq)]
7pub enum NetAccess {
8    /// No network access at all (fail-safe default).
9    #[default]
10    Denied,
11    /// Unrestricted access, matching a bare `--allow-net`.
12    Allowed,
13    /// Access restricted to the given domains (and any path under them).
14    AllowedDomains(Vec<String>),
15}
16
17impl From<bool> for NetAccess {
18    fn from(allow: bool) -> Self {
19        if allow { NetAccess::Allowed } else { NetAccess::Denied }
20    }
21}
22
23impl From<Vec<String>> for NetAccess {
24    fn from(domains: Vec<String>) -> Self {
25        if domains.is_empty() {
26            NetAccess::Allowed
27        } else {
28            NetAccess::AllowedDomains(domains)
29        }
30    }
31}
32
33impl From<Option<Vec<String>>> for NetAccess {
34    fn from(domains: Option<Vec<String>>) -> Self {
35        match domains {
36            None => NetAccess::Denied,
37            Some(domains) => domains.into(),
38        }
39    }
40}
41
42impl NetAccess {
43    pub(super) fn permits(&self, url: &str) -> bool {
44        match self {
45            NetAccess::Denied => false,
46            NetAccess::Allowed => true,
47            NetAccess::AllowedDomains(allowed) => allowed.iter().any(|domain| url_allowlist::matches(url, domain)),
48        }
49    }
50
51    pub(super) fn is_denied(&self) -> bool {
52        matches!(self, NetAccess::Denied)
53    }
54}