1use std::future::Future;
4use std::pin::Pin;
5use std::sync::Arc;
6
7use crate::network_policy::{CompiledNetworkPolicy, NetworkVerdict};
8
9#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct DomainRequest {
13 pub host: String,
15 pub port: u16,
17 pub agent: Option<String>,
20}
21
22pub trait DomainApprover: Send + Sync {
30 fn approve(&self, request: &DomainRequest) -> impl Future<Output = bool> + Send;
32}
33
34#[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#[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
55trait 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#[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 #[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#[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 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}