Skip to main content

aither_sandbox/
network_policy.rs

1//! Declarative host-based network policy.
2//!
3//! Applications describe which hosts sandboxed commands may reach as a
4//! serializable [`NetworkPolicyConfig`]; compiling it yields a
5//! [`CompiledNetworkPolicy`] a [`Sandbox`](crate::Sandbox) consults for every
6//! connection. A host the lists allow or deny is decided there; one they
7//! leave [open](NetworkVerdict::Open) goes to the sandbox's
8//! [`DomainApprover`](crate::DomainApprover).
9
10use globset::{Glob, GlobSet, GlobSetBuilder};
11
12/// Global network restriction mode.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, Default)]
14#[serde(rename_all = "snake_case")]
15pub enum NetworkPolicyMode {
16    /// No restrictions: every domain is allowed.
17    #[default]
18    Disabled,
19    /// Deny all network access.
20    Restricted,
21    /// Allow only hosts matching the configured patterns.
22    AllowList,
23    /// Allow everything except hosts matching the configured patterns.
24    DenyList,
25}
26
27impl NetworkPolicyMode {
28    /// Stable `snake_case` identifier for persistence and telemetry.
29    #[must_use]
30    pub const fn as_str(self) -> &'static str {
31        match self {
32            Self::Disabled => "disabled",
33            Self::Restricted => "restricted",
34            Self::AllowList => "allow_list",
35            Self::DenyList => "deny_list",
36        }
37    }
38}
39
40/// Error compiling a [`NetworkPolicyConfig`].
41#[derive(Debug, thiserror::Error)]
42pub enum NetworkPolicyError {
43    /// A configured host entry is not a valid glob pattern.
44    #[error("invalid network host pattern '{pattern}': {source}")]
45    InvalidPattern {
46        /// The offending host pattern as configured.
47        pattern: String,
48        /// The underlying glob parse error.
49        source: globset::Error,
50    },
51    /// The combined host matcher could not be built.
52    #[error("failed to build host matcher: {0}")]
53    Matcher(#[source] globset::Error),
54}
55
56/// Persisted network policy settings.
57#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
58#[serde(rename_all = "camelCase")]
59pub struct NetworkPolicyConfig {
60    /// Global restriction mode.
61    #[serde(default)]
62    pub mode: NetworkPolicyMode,
63    /// Host patterns interpreted according to [`NetworkPolicyMode`].
64    #[serde(default)]
65    pub hosts: Vec<String>,
66}
67
68impl NetworkPolicyConfig {
69    /// Whether the policy restricts anything at all.
70    #[must_use]
71    pub const fn is_active(&self) -> bool {
72        !matches!(self.mode, NetworkPolicyMode::Disabled)
73    }
74
75    /// Compile the settings into a matchable policy.
76    ///
77    /// Returns `Ok(None)` when the policy is disabled.
78    ///
79    /// # Errors
80    /// Returns an error when a configured host pattern is not a valid glob
81    /// or the combined matcher cannot be built.
82    pub fn compile(&self) -> Result<Option<CompiledNetworkPolicy>, NetworkPolicyError> {
83        if !self.is_active() {
84            return Ok(None);
85        }
86
87        let hosts = self
88            .hosts
89            .iter()
90            .map(|value| value.trim().to_ascii_lowercase())
91            .filter(|value| !value.is_empty())
92            .collect::<Vec<_>>();
93
94        let matcher = if matches!(
95            self.mode,
96            NetworkPolicyMode::AllowList | NetworkPolicyMode::DenyList
97        ) {
98            Some(build_matcher(&hosts)?)
99        } else {
100            None
101        };
102
103        Ok(Some(CompiledNetworkPolicy {
104            mode: self.mode,
105            hosts,
106            matcher,
107        }))
108    }
109}
110
111/// What a compiled network policy decides about a host.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum NetworkVerdict {
114    /// The lists allow the host.
115    Allowed,
116    /// The lists deny the host.
117    Denied,
118    /// The lists do not decide: an allow-list does not name the host. The
119    /// sandbox's approver decides.
120    Open,
121}
122
123/// A compiled, matchable network policy.
124#[derive(Debug, Clone)]
125pub struct CompiledNetworkPolicy {
126    mode: NetworkPolicyMode,
127    hosts: Vec<String>,
128    matcher: Option<GlobSet>,
129}
130
131impl CompiledNetworkPolicy {
132    /// The mode this policy was compiled from.
133    #[must_use]
134    pub const fn mode(&self) -> NetworkPolicyMode {
135        self.mode
136    }
137
138    /// Normalized host patterns this policy matches against.
139    #[must_use]
140    pub fn hosts(&self) -> &[String] {
141        &self.hosts
142    }
143
144    /// Whether the policy permits connecting to `domain`.
145    #[must_use]
146    pub fn allows_domain(&self, domain: &str) -> bool {
147        let normalized = domain.trim().to_ascii_lowercase();
148        match self.mode {
149            NetworkPolicyMode::Disabled => true,
150            NetworkPolicyMode::Restricted => false,
151            NetworkPolicyMode::AllowList => self
152                .matcher
153                .as_ref()
154                .is_some_and(|matcher| matcher.is_match(normalized.as_str())),
155            NetworkPolicyMode::DenyList => !self
156                .matcher
157                .as_ref()
158                .is_some_and(|matcher| matcher.is_match(normalized.as_str())),
159        }
160    }
161}
162
163impl CompiledNetworkPolicy {
164    /// What the lists decide about `domain`: the verdict of
165    /// [`allows_domain`](Self::allows_domain), except that an allow-list that
166    /// does not name the host leaves it [open](NetworkVerdict::Open) for the
167    /// approver instead of denying it.
168    #[must_use]
169    pub fn verdict(&self, domain: &str) -> NetworkVerdict {
170        match (self.mode, self.allows_domain(domain)) {
171            (_, true) => NetworkVerdict::Allowed,
172            (NetworkPolicyMode::AllowList, false) => NetworkVerdict::Open,
173            (_, false) => NetworkVerdict::Denied,
174        }
175    }
176}
177
178fn build_matcher(hosts: &[String]) -> Result<GlobSet, NetworkPolicyError> {
179    let mut builder = GlobSetBuilder::new();
180    for host in hosts {
181        let glob = Glob::new(host).map_err(|source| NetworkPolicyError::InvalidPattern {
182            pattern: host.clone(),
183            source,
184        })?;
185        builder.add(glob);
186    }
187    builder.build().map_err(NetworkPolicyError::Matcher)
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn restricted_policy_blocks_everything() {
196        let policy = NetworkPolicyConfig {
197            mode: NetworkPolicyMode::Restricted,
198            hosts: Vec::new(),
199        }
200        .compile()
201        .expect("restricted policy should compile")
202        .expect("restricted policy should be active");
203        assert!(!policy.allows_domain("example.com"));
204    }
205
206    #[test]
207    fn allow_list_policy_matches_globs() {
208        let policy = NetworkPolicyConfig {
209            mode: NetworkPolicyMode::AllowList,
210            hosts: vec!["*.example.com".to_string()],
211        }
212        .compile()
213        .expect("allow list should compile")
214        .expect("allow list should be active");
215        assert!(policy.allows_domain("api.example.com"));
216        assert!(!policy.allows_domain("example.org"));
217    }
218
219    #[test]
220    fn deny_list_policy_blocks_matches_only() {
221        let policy = NetworkPolicyConfig {
222            mode: NetworkPolicyMode::DenyList,
223            hosts: vec!["*.tracker.net".to_string()],
224        }
225        .compile()
226        .expect("deny list should compile")
227        .expect("deny list should be active");
228        assert!(!policy.allows_domain("ads.tracker.net"));
229        assert!(policy.allows_domain("api.github.com"));
230    }
231
232    #[test]
233    fn disabled_policy_compiles_to_none() {
234        let compiled = NetworkPolicyConfig::default()
235            .compile()
236            .expect("disabled policy should compile");
237        assert!(compiled.is_none());
238    }
239
240    #[test]
241    fn invalid_pattern_reports_offending_host() {
242        let error = NetworkPolicyConfig {
243            mode: NetworkPolicyMode::AllowList,
244            hosts: vec!["[".to_string()],
245        }
246        .compile()
247        .expect_err("invalid glob must fail compilation");
248        assert!(error.to_string().contains('['));
249    }
250}