Skip to main content

aither_sandbox/spawn/
domain.rs

1//! Approval of the network domains a sandbox's lists leave open.
2
3use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use crate::network_policy::{CompiledNetworkPolicy, NetworkVerdict};
8
9/// One connection a sandboxed process makes to a domain the network lists
10/// leave open.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct DomainRequest {
13    /// The host being connected to.
14    pub host: String,
15    /// The port being connected to.
16    pub port: u16,
17    /// The agent whose sandbox the process runs in, as the embedder labelled
18    /// the sandbox; `None` for an unlabelled sandbox.
19    pub agent: Option<String>,
20}
21
22/// Decides the connections the sandbox's network lists leave open.
23///
24/// The sandbox consults its [`CompiledNetworkPolicy`] first: a host the lists
25/// allow or deny never reaches the approver. For the rest it asks
26/// [`approve`](Self::approve) once per connection and enforces the answer for
27/// that connection. Auditing, asking a user, a reviewer and remembering an
28/// approval are the implementation's policy.
29pub trait DomainApprover: Send + Sync {
30    /// Whether the process may connect to `request`'s host and port.
31    fn approve(&self, request: &DomainRequest) -> impl Future<Output = bool> + Send;
32}
33
34/// Approves every domain it is asked about.
35#[derive(Debug, Clone, Copy, Default)]
36pub struct ApproveAllDomains;
37
38impl DomainApprover for ApproveAllDomains {
39    fn approve(&self, _request: &DomainRequest) -> impl Future<Output = bool> + Send {
40        std::future::ready(true)
41    }
42}
43
44/// Denies every domain it is asked about, which is what a sandbox without an
45/// approver does.
46#[derive(Debug, Clone, Copy, Default)]
47pub struct DenyAllDomains;
48
49impl DomainApprover for DenyAllDomains {
50    fn approve(&self, _request: &DomainRequest) -> impl Future<Output = bool> + Send {
51        std::future::ready(false)
52    }
53}
54
55/// Object-safe twin of [`DomainApprover`], used only through
56/// [`AnyDomainApprover`].
57trait DomainApproverImpl: Send + Sync {
58    fn approve_boxed<'a>(
59        &'a self,
60        request: &'a DomainRequest,
61    ) -> Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
62}
63
64impl<T: DomainApprover> DomainApproverImpl for T {
65    fn approve_boxed<'a>(
66        &'a self,
67        request: &'a DomainRequest,
68    ) -> Pin<Box<dyn Future<Output = bool> + Send + 'a>> {
69        Box::pin(self.approve(request))
70    }
71}
72
73/// A cloneable handle on any [`DomainApprover`].
74#[derive(Clone)]
75pub struct AnyDomainApprover(Arc<dyn DomainApproverImpl>);
76
77impl std::fmt::Debug for AnyDomainApprover {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("AnyDomainApprover").finish_non_exhaustive()
80    }
81}
82
83impl AnyDomainApprover {
84    /// Wraps a concrete approver.
85    #[must_use]
86    pub fn new(approver: impl DomainApprover + 'static) -> Self {
87        Self(Arc::new(approver))
88    }
89}
90
91impl DomainApprover for AnyDomainApprover {
92    fn approve(&self, request: &DomainRequest) -> impl Future<Output = bool> + Send {
93        let inner = Arc::clone(&self.0);
94        let request = request.clone();
95        async move { inner.approve_boxed(&request).await }
96    }
97}
98
99/// The network policy a sandbox hands heel: the lists first, then the
100/// approver for what they leave open, and a denial when there is none.
101#[derive(Clone)]
102pub struct DomainGate {
103    pub(crate) lists: Option<CompiledNetworkPolicy>,
104    pub(crate) approver: Option<AnyDomainApprover>,
105    pub(crate) agent: Option<Arc<str>>,
106}
107
108impl DomainGate {
109    pub(crate) async fn decide(&self, host: &str, port: u16) -> bool {
110        let verdict = self
111            .lists
112            .as_ref()
113            .map_or(NetworkVerdict::Open, |lists| lists.verdict(host));
114        match verdict {
115            NetworkVerdict::Allowed => true,
116            NetworkVerdict::Denied => false,
117            NetworkVerdict::Open => match &self.approver {
118                Some(approver) => {
119                    approver
120                        .approve(&DomainRequest {
121                            host: host.to_string(),
122                            port,
123                            agent: self.agent.as_deref().map(str::to_string),
124                        })
125                        .await
126                }
127                None => false,
128            },
129        }
130    }
131}
132
133impl heel::NetworkPolicy for DomainGate {
134    async fn check(&self, request: &heel::DomainRequest) -> bool {
135        self.decide(request.host(), request.port()).await
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use std::sync::Mutex;
142
143    use super::*;
144    use crate::{NetworkPolicyConfig, NetworkPolicyMode};
145
146    /// Records what it is asked and answers a fixed verdict.
147    struct Recording {
148        answer: bool,
149        asked: Arc<Mutex<Vec<DomainRequest>>>,
150    }
151
152    impl DomainApprover for Recording {
153        fn approve(&self, request: &DomainRequest) -> impl Future<Output = bool> + Send {
154            self.asked.lock().unwrap().push(request.clone());
155            std::future::ready(self.answer)
156        }
157    }
158
159    fn gate(
160        mode: NetworkPolicyMode,
161        hosts: &[&str],
162        answer: Option<bool>,
163    ) -> (DomainGate, Arc<Mutex<Vec<DomainRequest>>>) {
164        let asked = Arc::new(Mutex::new(Vec::new()));
165        let lists = NetworkPolicyConfig {
166            mode,
167            hosts: hosts.iter().map(|host| (*host).to_string()).collect(),
168        }
169        .compile()
170        .unwrap();
171        let approver = answer.map(|answer| {
172            AnyDomainApprover::new(Recording {
173                answer,
174                asked: asked.clone(),
175            })
176        });
177        (
178            DomainGate {
179                lists,
180                approver,
181                agent: Some(Arc::from("worker")),
182            },
183            asked,
184        )
185    }
186
187    #[tokio::test]
188    async fn a_domain_the_lists_leave_open_reaches_the_approver_with_host_port_and_agent() {
189        let (gate, asked) = gate(NetworkPolicyMode::AllowList, &["*.example.com"], Some(true));
190        assert!(gate.decide("registry.other.org", 8443).await);
191        assert_eq!(
192            *asked.lock().unwrap(),
193            [DomainRequest {
194                host: "registry.other.org".into(),
195                port: 8443,
196                agent: Some("worker".into()),
197            }]
198        );
199    }
200
201    #[tokio::test]
202    async fn the_approvers_answer_is_enforced_for_the_connection() {
203        let (refusing, asked) = gate(
204            NetworkPolicyMode::AllowList,
205            &["*.example.com"],
206            Some(false),
207        );
208        assert!(!refusing.decide("registry.other.org", 443).await);
209        assert_eq!(asked.lock().unwrap().len(), 1);
210    }
211
212    #[tokio::test]
213    async fn a_domain_the_lists_decide_never_reaches_the_approver() {
214        let (allow, asked) = gate(
215            NetworkPolicyMode::AllowList,
216            &["*.example.com"],
217            Some(false),
218        );
219        assert!(allow.decide("api.example.com", 443).await);
220        let (deny, denied_asked) =
221            gate(NetworkPolicyMode::DenyList, &["*.tracker.net"], Some(true));
222        assert!(!deny.decide("ads.tracker.net", 443).await);
223        let (restricted, restricted_asked) = gate(NetworkPolicyMode::Restricted, &[], Some(true));
224        assert!(!restricted.decide("example.com", 443).await);
225        for asked in [asked, denied_asked, restricted_asked] {
226            assert!(asked.lock().unwrap().is_empty());
227        }
228    }
229
230    #[tokio::test]
231    async fn without_lists_every_domain_is_open_and_without_an_approver_denied() {
232        let (asking, asked) = gate(NetworkPolicyMode::Disabled, &[], Some(true));
233        assert!(asking.decide("example.com", 80).await);
234        assert_eq!(asked.lock().unwrap().len(), 1);
235        let (none, _) = gate(NetworkPolicyMode::Disabled, &[], None);
236        assert!(!none.decide("example.com", 80).await);
237    }
238}