Skip to main content

rtci_host/
gate.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! The net permission gate ([`NetGate`]): every address the engine reaches,
4//! every socket it binds and the machine's interface list go through it
5//! first.
6//!
7//! The engine first calls [`NetGate::decide`] (or [`NetGate::interfaces`]).
8//! A gate that answers there (a runtime's permission set) is synchronous,
9//! and the engine behaves as if nothing were asynchronous. When `decide`
10//! returns `None`, the engine calls [`NetGate::ask`] once for that question
11//! and waits for the answer, holding back whatever needed it: no socket is
12//! bound, no name resolved and no datagram sent until the answer is
13//! [`Verdict::Allow`]. An answer that doesn't come within
14//! [`NetGate::ask_timeout`], a gate that panics, and a dropped request are
15//! refusals (deny by default). [`AskGate`](crate::AskGate) is a ready-made
16//! asynchronous gate whose questions a front end answers by ticket.
17//!
18//! Every [`NetIo`](crate::NetIo) call that creates a socket or resolves a
19//! name takes a [`GateToken`], which only the engine mints, from an allow
20//! for the matching [`Reach`].
21
22use std::fmt;
23use std::future::Future;
24use std::net::IpAddr;
25use std::net::SocketAddr;
26use std::pin::Pin;
27use std::time::Duration;
28
29/// A boxed, `!Send` future (the engine is single-threaded).
30pub type LocalBoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
31
32/// The transport of a [`Reach`].
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum Proto {
35  Udp,
36  Tcp,
37  Tls,
38}
39
40impl Proto {
41  /// `"udp"`, `"tcp"` or `"tls"` (the `proto` of a `gaterequest`).
42  pub fn as_str(self) -> &'static str {
43    match self {
44      Proto::Udp => "udp",
45      Proto::Tcp => "tcp",
46      Proto::Tls => "tls",
47    }
48  }
49}
50
51/// Whether a [`Reach`] sends to an address or binds one.
52#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
53pub enum Direction {
54  Connect,
55  Listen,
56}
57
58impl Direction {
59  /// `"connect"` or `"listen"` (the `dir` of a `gaterequest`).
60  pub fn as_str(self) -> &'static str {
61    match self {
62      Direction::Connect => "connect",
63      Direction::Listen => "listen",
64    }
65  }
66}
67
68/// Why the engine asks (for logs and prompts; a gate may also decide on
69/// it). The engine's cache of asked answers ignores the kind: an answer for
70/// one kind is reused for another with the same direction, transport, host,
71/// port and `resolved_from`.
72#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
73#[non_exhaustive]
74pub enum ReachKind {
75  /// An ICE server URL's host, before DNS.
76  IceServer,
77  /// The address an ICE server's host resolved to.
78  IceServerResolved,
79  /// A remote candidate's address (`setRemoteDescription`,
80  /// `addIceCandidate`).
81  RemoteCandidate,
82  /// The first datagram to a new address (a peer-reflexive or
83  /// mDNS-resolved candidate, a relayed peer, ...).
84  SendTo,
85  /// An ICE-TCP active dial.
86  TcpDial,
87  /// A UDP or TCP bind on an IP.
88  Bind,
89  /// The mDNS socket: binding `0.0.0.0:5353` and sending to
90  /// `224.0.0.251:5353`.
91  Mdns,
92}
93
94impl ReachKind {
95  /// The kind's name in a `gaterequest` (`"iceServer"`,
96  /// `"iceServerResolved"`, `"remoteCandidate"`, `"sendTo"`, `"tcpDial"`,
97  /// `"bind"`, `"mdns"`).
98  pub fn as_str(self) -> &'static str {
99    match self {
100      ReachKind::IceServer => "iceServer",
101      ReachKind::IceServerResolved => "iceServerResolved",
102      ReachKind::RemoteCandidate => "remoteCandidate",
103      ReachKind::SendTo => "sendTo",
104      ReachKind::TcpDial => "tcpDial",
105      ReachKind::Bind => "bind",
106      ReachKind::Mdns => "mdns",
107    }
108  }
109}
110
111/// A host a [`Reach`] names: a name (an ICE server URL's host, before DNS)
112/// or an IP address.
113#[derive(Clone, Debug, PartialEq, Eq, Hash)]
114pub enum Host {
115  Name(String),
116  Ip(IpAddr),
117}
118
119impl fmt::Display for Host {
120  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121    match self {
122      Host::Name(name) => f.write_str(name),
123      Host::Ip(ip) => ip.fmt(f),
124    }
125  }
126}
127
128/// One thing the engine wants to reach.
129#[derive(Clone, Debug, PartialEq, Eq, Hash)]
130pub struct Reach {
131  pub kind: ReachKind,
132  pub dir: Direction,
133  pub proto: Proto,
134  pub host: Host,
135  /// The port, where the engine knows it. A [`ReachKind::Bind`] carries
136  /// none: the permission is for the IP, whatever port the OS picks.
137  pub port: Option<u16>,
138  /// For [`ReachKind::IceServerResolved`]: the host name it was resolved
139  /// from.
140  pub resolved_from: Option<String>,
141}
142
143impl Reach {
144  /// Sending to `addr`.
145  pub fn connect(kind: ReachKind, proto: Proto, addr: SocketAddr) -> Self {
146    Self {
147      kind,
148      dir: Direction::Connect,
149      proto,
150      host: Host::Ip(addr.ip()),
151      port: Some(addr.port()),
152      resolved_from: None,
153    }
154  }
155
156  /// Binding a socket on `ip` (any port).
157  pub fn bind(kind: ReachKind, proto: Proto, ip: IpAddr) -> Self {
158    Self {
159      kind,
160      dir: Direction::Listen,
161      proto,
162      host: Host::Ip(ip),
163      port: None,
164      resolved_from: None,
165    }
166  }
167
168  /// An ICE server URL's host and port, before DNS.
169  pub fn ice_server(proto: Proto, host: &str, port: u16) -> Self {
170    Self {
171      kind: ReachKind::IceServer,
172      dir: Direction::Connect,
173      proto,
174      host: Host::Name(host.to_string()),
175      port: Some(port),
176      resolved_from: None,
177    }
178  }
179
180  /// The socket address, for an IP host with a port.
181  pub fn socket_addr(&self) -> Option<SocketAddr> {
182    match (&self.host, self.port) {
183      (Host::Ip(ip), Some(port)) => Some(SocketAddr::new(*ip, port)),
184      _ => None,
185    }
186  }
187}
188
189/// A gate's answer.
190#[derive(Clone, Debug, PartialEq, Eq)]
191pub enum Verdict {
192  Allow,
193  /// Refused, with the message the engine reports (an
194  /// `icecandidateerror`'s text, or a [`NotCapable`] error's message).
195  ///
196  /// [`NotCapable`]: crate::ErrorKind::NotCapable
197  Deny(String),
198}
199
200impl Verdict {
201  pub fn is_allow(&self) -> bool {
202    matches!(self, Verdict::Allow)
203  }
204
205  /// `Ok(())` for [`Verdict::Allow`], else the refusal's message.
206  pub fn into_result(self) -> Result<(), String> {
207    match self {
208      Verdict::Allow => Ok(()),
209      Verdict::Deny(message) => Err(message),
210    }
211  }
212}
213
214/// How long the engine waits for an asked answer by default
215/// ([`NetGate::ask_timeout`]).
216pub const DEFAULT_ASK_TIMEOUT: Duration = Duration::from_secs(10);
217
218/// The net permission gate. There is no allowing default: every
219/// [`Peer`](crate::Peer), [`Network`](crate::Network) and
220/// [`IceTransport`](crate::IceTransport) is given one, and [`DenyAllGate`]
221/// refuses everything.
222pub trait NetGate {
223  /// Answers now if it can. A gate that answers synchronously (a runtime's
224  /// permission set) always returns `Some`; `None` makes the engine
225  /// [`ask`](NetGate::ask). Called again each time the engine needs the
226  /// question answered, so it may answer from a cache of its own.
227  fn decide(&self, reach: &Reach) -> Option<Verdict>;
228
229  /// Asks, the answer arriving through the returned future. Called only
230  /// after `decide` returned `None`, at most once per question at a time
231  /// per connection (the engine dedupes and remembers the answer). The
232  /// future is dropped when the connection closes or
233  /// [`NetGate::ask_timeout`] passes (a refusal). The default answers from
234  /// [`NetGate::decide`] (`None` is a refusal).
235  fn ask(&self, reach: Reach) -> LocalBoxFuture<'static, Verdict> {
236    let verdict = self.decide(&reach).unwrap_or_else(|| pending(&reach));
237    Box::pin(std::future::ready(verdict))
238  }
239
240  /// May the engine list the machine's interface addresses (its host
241  /// candidates beyond loopback)? (Deno's `--allow-sys=networkInterfaces`.)
242  fn interfaces(&self) -> Option<Verdict>;
243
244  /// [`NetGate::interfaces`], asked. The default answers from
245  /// `interfaces()` (`None` is a refusal).
246  fn ask_interfaces(&self) -> LocalBoxFuture<'static, Verdict> {
247    let verdict = self.interfaces().unwrap_or_else(|| {
248      Verdict::Deny("The network interfaces were not allowed".to_string())
249    });
250    Box::pin(std::future::ready(verdict))
251  }
252
253  /// How long the engine waits for an [`ask`](NetGate::ask) /
254  /// [`ask_interfaces`](NetGate::ask_interfaces) answer before it takes
255  /// the question as refused.
256  fn ask_timeout(&self) -> Duration {
257    DEFAULT_ASK_TIMEOUT
258  }
259}
260
261/// Proof that the gate allowed a [`Reach`]: every [`NetIo`](crate::NetIo)
262/// call that creates a socket or resolves a name takes one. Only the engine
263/// mints them (there is no public constructor), from an allow for the
264/// `Reach` the call is for, so a `NetIo` implementation may check
265/// [`GateToken::reach`] against its arguments.
266#[derive(Clone, Debug, PartialEq, Eq)]
267pub struct GateToken {
268  reach: Reach,
269}
270
271impl GateToken {
272  /// Only after an allow for `reach`.
273  pub(crate) fn new(reach: Reach) -> Self {
274    Self { reach }
275  }
276
277  /// The question the gate allowed.
278  pub fn reach(&self) -> &Reach {
279    &self.reach
280  }
281}
282
283/// What an answer is remembered by: a [`Reach`] without its kind.
284#[derive(Clone, Debug, PartialEq, Eq, Hash)]
285pub(crate) struct ReachKey {
286  dir: Direction,
287  proto: Proto,
288  host: Host,
289  port: Option<u16>,
290  resolved_from: Option<String>,
291}
292
293impl From<&Reach> for ReachKey {
294  fn from(r: &Reach) -> Self {
295    Self {
296      dir: r.dir,
297      proto: r.proto,
298      host: r.host.clone(),
299      port: r.port,
300      resolved_from: r.resolved_from.clone(),
301    }
302  }
303}
304
305/// Refuses everything.
306#[derive(Clone, Copy, Debug, Default)]
307pub struct DenyAllGate;
308
309impl NetGate for DenyAllGate {
310  fn decide(&self, reach: &Reach) -> Option<Verdict> {
311    Some(Verdict::Deny(format!(
312      "Requires net access to \"{}\"",
313      describe(reach)
314    )))
315  }
316
317  fn interfaces(&self) -> Option<Verdict> {
318    Some(Verdict::Deny(
319      "Requires sys access to \"networkInterfaces\"".to_string(),
320    ))
321  }
322}
323
324/// The refusal for a `decide` that had no answer.
325pub(crate) fn pending(reach: &Reach) -> Verdict {
326  Verdict::Deny(format!(
327    "Net access to \"{}\" was not decided",
328    describe(reach)
329  ))
330}
331
332pub(crate) fn describe(reach: &Reach) -> String {
333  match (&reach.host, reach.port) {
334    (Host::Ip(IpAddr::V6(ip)), Some(port)) => format!("[{ip}]:{port}"),
335    (host, Some(port)) => format!("{host}:{port}"),
336    (host, None) => host.to_string(),
337  }
338}
339
340/// The refusal for an `interfaces()` that had no answer.
341pub(crate) fn interfaces_pending() -> Verdict {
342  Verdict::Deny("The network interfaces were not allowed".to_string())
343}
344
345/// The synchronous questions (`None` answers refused): the callers that
346/// can't wait ([`crate::check_ice_servers`], [`crate::Network::new`]).
347pub(crate) trait GateExt {
348  fn check(&self, reach: &Reach) -> Result<(), String>;
349  fn check_interfaces(&self) -> Result<(), String>;
350}
351
352impl<G: NetGate + ?Sized> GateExt for G {
353  fn check(&self, reach: &Reach) -> Result<(), String> {
354    self
355      .decide(reach)
356      .unwrap_or_else(|| pending(reach))
357      .into_result()
358  }
359
360  fn check_interfaces(&self) -> Result<(), String> {
361    self
362      .interfaces()
363      .unwrap_or_else(|| {
364        Verdict::Deny("The network interfaces were not allowed".to_string())
365      })
366      .into_result()
367  }
368}