Skip to main content

rings_node/onion/
role.rs

1//! Onion roles: the symbols one node process registers (#834 D2).
2//!
3//! A node process is a partial Σ-algebra, and registering any symbol registers `relay`:
4//!
5//! ```text
6//! Reg_n ∈ { ∅,      {relay}, {relay} ⊎ Reg_I, {relay} ⊎ Reg_W, {relay} ⊎ Reg_W ⊎ Reg_I }
7//!           Client  Relay    Invoke(i)        Exit(x)          Both { exit: x, invoke: i }
8//! ```
9//!
10//! [`OnionRole<X, I>`] encodes that lattice so neither "exit without relay" nor "invoke without
11//! relay" has an inhabitant (`Reg_n ≠ ∅ ⇒ relay ∈ Reg_n`). `OnionRole` is functorial in `X`
12//! ([`OnionRole::map`]) and defaults `I = OnionInvokeOffer`. The processor holds one
13//! `OnionRole<OnionExitOffer>`, and every layer of the node reads that value:
14//!
15//! - online-node relay capability (`registers_relay()`),
16//! - world-facing exit descriptors (`exit()`),
17//! - intermediate `invoke` descriptors (`invoke()`), and
18//! - the data plane's admission and Σ-algebra.
19
20use std::collections::BTreeMap;
21use std::collections::BTreeSet;
22
23use super::invoke_descriptor::OnionInvokePolicy;
24use super::signature::OnionBackendName;
25use super::signature::OnionInvokeShape;
26use super::OnionExitPolicy;
27use super::OnionServiceName;
28use crate::error::Error;
29use crate::error::Result;
30
31/// The registration role of one node process over `Σ = {relay} ⊎ Σ_I ⊎ Σ_W` (#834 D2).
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub enum OnionRole<X, I = OnionInvokeOffer> {
34    /// Registers no symbol: builds loops, evaluates no position.
35    Client,
36    /// Registers `relay` only.
37    Relay,
38    /// Registers `relay` and the intermediate `(shape, backend)` pairs of `I`.
39    Invoke(I),
40    /// Registers `relay` and the world-facing symbols of `X`.
41    Exit(X),
42    /// Registers `relay`, the world-facing symbols of `X`, and the intermediate pairs of `I`.
43    Both {
44        /// World-facing exit offer.
45        exit: X,
46        /// Intermediate `invoke` offer.
47        invoke: I,
48    },
49}
50
51impl<X, I> OnionRole<X, I> {
52    /// Return whether this role registers `relay`: every rung above [`OnionRole::Client`].
53    pub const fn registers_relay(&self) -> bool {
54        !matches!(self, Self::Client)
55    }
56
57    /// Return the exit's data when this role registers world-facing symbols.
58    pub const fn exit(&self) -> Option<&X> {
59        match self {
60            Self::Exit(exit) | Self::Both { exit, .. } => Some(exit),
61            Self::Client | Self::Relay | Self::Invoke(_) => None,
62        }
63    }
64
65    /// Return the `invoke` offer when this role registers intermediate `(shape, backend)` pairs.
66    pub const fn invoke(&self) -> Option<&I> {
67        match self {
68            Self::Invoke(invoke) | Self::Both { invoke, .. } => Some(invoke),
69            Self::Client | Self::Relay | Self::Exit(_) => None,
70        }
71    }
72
73    /// Borrow the role's offers: `OnionRole<X, I> → OnionRole<&X, &I>`.
74    pub const fn as_ref(&self) -> OnionRole<&X, &I> {
75        match self {
76            Self::Client => OnionRole::Client,
77            Self::Relay => OnionRole::Relay,
78            Self::Invoke(invoke) => OnionRole::Invoke(invoke),
79            Self::Exit(exit) => OnionRole::Exit(exit),
80            Self::Both { exit, invoke } => OnionRole::Both { exit, invoke },
81        }
82    }
83
84    /// Relabel the exit's data, preserving the rung: the functor action in `X`.
85    pub fn map<Y>(self, exit: impl FnOnce(X) -> Y) -> OnionRole<Y, I> {
86        match self {
87            Self::Client => OnionRole::Client,
88            Self::Relay => OnionRole::Relay,
89            Self::Invoke(invoke) => OnionRole::Invoke(invoke),
90            Self::Exit(data) => OnionRole::Exit(exit(data)),
91            Self::Both { exit: data, invoke } => OnionRole::Both {
92                exit: exit(data),
93                invoke,
94            },
95        }
96    }
97
98    /// Relabel the exit's data by a fallible function, preserving the rung.
99    pub fn try_map<Y, E>(
100        self,
101        exit: impl FnOnce(X) -> std::result::Result<Y, E>,
102    ) -> std::result::Result<OnionRole<Y, I>, E> {
103        match self {
104            Self::Client => Ok(OnionRole::Client),
105            Self::Relay => Ok(OnionRole::Relay),
106            Self::Invoke(invoke) => Ok(OnionRole::Invoke(invoke)),
107            Self::Exit(data) => exit(data).map(OnionRole::Exit),
108            Self::Both { exit: data, invoke } => Ok(OnionRole::Both {
109                exit: exit(data)?,
110                invoke,
111            }),
112        }
113    }
114
115    /// Attach an intermediate `invoke` offer to this role, promoting `Client`/`Relay` to `Invoke`
116    /// and `Exit` to `Both` (`Reg_n ≠ ∅ ⇒ relay ∈ Reg_n`).
117    pub fn with_invoke(self, invoke: I) -> Self {
118        match self {
119            Self::Client | Self::Relay | Self::Invoke(_) => Self::Invoke(invoke),
120            Self::Exit(exit) | Self::Both { exit, .. } => Self::Both { exit, invoke },
121        }
122    }
123}
124
125/// What a node offers for intermediate `invoke` evaluation: a non-empty map from `(shape, backend)`
126/// pairs in `Σ_I × Ω` to their signed `quota(n, f, ω)` policies (#834 D2).
127#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
128#[serde(
129    try_from = "Vec<SerializedOnionInvokeEntry>",
130    into = "Vec<SerializedOnionInvokeEntry>"
131)]
132pub struct OnionInvokeOffer {
133    entries: BTreeMap<(OnionInvokeShape, OnionBackendName), OnionInvokePolicy>,
134}
135
136#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
137struct SerializedOnionInvokeEntry {
138    shape: OnionInvokeShape,
139    backend: OnionBackendName,
140    #[serde(default)]
141    policy: OnionInvokePolicy,
142}
143
144impl From<OnionInvokeOffer> for Vec<SerializedOnionInvokeEntry> {
145    fn from(offer: OnionInvokeOffer) -> Self {
146        offer
147            .entries
148            .into_iter()
149            .map(|((shape, backend), policy)| SerializedOnionInvokeEntry {
150                shape,
151                backend,
152                policy,
153            })
154            .collect()
155    }
156}
157
158impl TryFrom<Vec<SerializedOnionInvokeEntry>> for OnionInvokeOffer {
159    type Error = Error;
160
161    fn try_from(entries: Vec<SerializedOnionInvokeEntry>) -> Result<Self> {
162        let mut collected = BTreeMap::new();
163        for entry in entries {
164            if collected
165                .insert((entry.shape, entry.backend.clone()), entry.policy)
166                .is_some()
167            {
168                return Err(Error::InvalidConfig(format!(
169                    "duplicate onion invoke entry for ({}, {:?})",
170                    entry.shape,
171                    entry.backend.as_str()
172                )));
173            }
174        }
175        if collected.is_empty() {
176            return Err(Error::InvalidConfig(
177                "an onion invoke offer requires at least one (shape, backend) entry".to_string(),
178            ));
179        }
180        Ok(Self { entries: collected })
181    }
182}
183
184impl OnionInvokeOffer {
185    /// Build an offer from `(shape, backend, policy)` entries, rejecting an empty set.
186    pub fn new(
187        entries: impl IntoIterator<Item = (OnionInvokeShape, OnionBackendName, OnionInvokePolicy)>,
188    ) -> Result<Self> {
189        let entries = entries
190            .into_iter()
191            .map(|(shape, backend, policy)| ((shape, backend), policy))
192            .collect::<BTreeMap<_, _>>();
193        if entries.is_empty() {
194            return Err(Error::InvalidConfig(
195                "an onion invoke offer requires at least one (shape, backend) entry".to_string(),
196            ));
197        }
198        Ok(Self { entries })
199    }
200
201    /// Iterate over offered `((shape, backend), policy)` entries in canonical order.
202    pub fn entries(
203        &self,
204    ) -> impl Iterator<Item = (&(OnionInvokeShape, OnionBackendName), &OnionInvokePolicy)> {
205        self.entries.iter()
206    }
207
208    /// Return the signed quota policy of `(shape, backend)`, if offered.
209    pub fn policy_for(
210        &self,
211        shape: OnionInvokeShape,
212        backend: &OnionBackendName,
213    ) -> Option<&OnionInvokePolicy> {
214        self.entries.get(&(shape, backend.clone()))
215    }
216}
217
218/// What an exit offers: a non-empty set of world-facing services under an open policy.
219///
220/// Invariant: `services` is non-empty and `policy` admits at least one target, so every value
221/// is an exit a client can route to. The services are a set, so each is registered once.
222#[derive(Clone, Debug, Eq, PartialEq)]
223pub struct OnionExitOffer {
224    services: BTreeSet<OnionServiceName>,
225    policy: OnionExitPolicy,
226}
227
228impl OnionExitOffer {
229    /// Build an offer, rejecting an empty service set and a closed policy.
230    pub fn new(
231        services: impl IntoIterator<Item = OnionServiceName>,
232        policy: OnionExitPolicy,
233    ) -> Result<Self> {
234        let services = services.into_iter().collect::<BTreeSet<_>>();
235        if services.is_empty() {
236            return Err(Error::InvalidConfig(
237                "an onion exit requires at least one onion_exit_services entry".to_string(),
238            ));
239        }
240        policy.validate_targets()?;
241        Ok(Self { services, policy })
242    }
243
244    /// Return the offered services, in name order.
245    pub const fn services(&self) -> &BTreeSet<OnionServiceName> {
246        &self.services
247    }
248
249    /// Return the policy shared by every offered service.
250    pub const fn policy(&self) -> &OnionExitPolicy {
251        &self.policy
252    }
253
254    /// Return whether this offer includes `service`.
255    pub fn offers(&self, service: &OnionServiceName) -> bool {
256        self.services.contains(service)
257    }
258
259    /// Return the first offered service this node's runtime cannot interpret, if any
260    /// (`runtime_interprets`).
261    pub fn uninterpretable_service(&self) -> Option<&OnionServiceName> {
262        self.services
263            .iter()
264            .find(|service| !runtime_interprets(service))
265    }
266}
267
268/// Return whether this node's runtime interprets the world-facing `service`: a native runtime
269/// interprets every one, a browser runtime, which has `fetch` but no sockets, only `https`.
270pub(crate) fn runtime_interprets(service: &OnionServiceName) -> bool {
271    cfg!(not(rings_browser)) || *service == OnionServiceName::https()
272}
273
274impl OnionRole<OnionExitOffer> {
275    /// Parse the textual registration flags of a configuration file or command line.
276    ///
277    /// The flags are the only place where "exit without relay" can be written; it is rejected
278    /// here, once, so no typed role can carry it. `services` and `policy` are read only for an
279    /// exit.
280    pub fn from_flags(
281        advertise_relay: bool,
282        advertise_exit: bool,
283        services: Vec<OnionServiceName>,
284        policy: OnionExitPolicy,
285    ) -> Result<Self> {
286        match (advertise_relay, advertise_exit) {
287            (false, false) => Ok(Self::Client),
288            (true, false) => Ok(Self::Relay),
289            (true, true) => OnionExitOffer::new(services, policy).map(Self::Exit),
290            (false, true) => Err(Error::InvalidConfig(
291                concat!(
292                    "advertise_onion_exit requires advertise_onion_relay because registering any ",
293                    "onion symbol registers relay (#834 D2)",
294                )
295                .to_string(),
296            )),
297        }
298    }
299}
300
301#[cfg(test)]
302mod tests {
303    use super::OnionExitOffer;
304    use super::OnionInvokeOffer;
305    use super::OnionRole;
306    use crate::error::Error;
307    use crate::error::Result;
308    use crate::onion::invoke_descriptor::OnionInvokePolicy;
309    use crate::onion::signature::OnionBackendName;
310    use crate::onion::signature::OnionInputType;
311    use crate::onion::signature::OnionInvokeShape;
312    use crate::onion::signature::OnionLatencyClass;
313    use crate::onion::signature::OnionWidthClass;
314    use crate::onion::OnionExitPolicy;
315    use crate::onion::OnionServiceName;
316
317    /// An open single-target policy.
318    fn open_policy() -> Result<OnionExitPolicy> {
319        OnionExitPolicy::from_target_strings(vec!["example.com:443".to_string()], Vec::new())
320    }
321
322    fn sample_invoke_offer() -> Result<OnionInvokeOffer> {
323        OnionInvokeOffer::new([(
324            OnionInvokeShape::new(
325                OnionInputType::Fixed(OnionWidthClass::B32),
326                OnionWidthClass::B64,
327                OnionLatencyClass::Ms500,
328            ),
329            OnionBackendName::parse("jev.typesafe")?,
330            OnionInvokePolicy::default(),
331        )])
332    }
333
334    /// The flags parse onto the ladder, and "exit without relay" is rejected.
335    #[test]
336    fn test_flags_parse_onto_the_registration_ladder() -> Result<()> {
337        let services = vec![OnionServiceName::tcp()];
338
339        assert_eq!(
340            OnionRole::from_flags(false, false, services.clone(), open_policy()?)?,
341            OnionRole::Client
342        );
343        assert_eq!(
344            OnionRole::from_flags(true, false, services.clone(), open_policy()?)?,
345            OnionRole::Relay
346        );
347        assert_eq!(
348            OnionRole::from_flags(true, true, services.clone(), open_policy()?)?,
349            OnionRole::Exit(OnionExitOffer::new(services.clone(), open_policy()?)?)
350        );
351        assert!(matches!(
352            OnionRole::from_flags(false, true, services, open_policy()?),
353            Err(Error::InvalidConfig(message))
354                if message.contains("advertise_onion_exit")
355                    && message.contains("advertise_onion_relay")
356        ));
357        Ok(())
358    }
359
360    /// `Invoke` and `Both` rungs enforce `registers_relay() == true` and reject empty offers (D2).
361    #[test]
362    fn test_invoke_offer_requires_entries_and_implies_relay() -> Result<()> {
363        assert!(OnionInvokeOffer::new([]).is_err());
364        let invoke = sample_invoke_offer()?;
365        let role_invoke = OnionRole::<OnionExitOffer>::Invoke(invoke.clone());
366        assert!(role_invoke.registers_relay());
367        assert!(role_invoke.exit().is_none());
368        assert_eq!(role_invoke.invoke(), Some(&invoke));
369
370        let exit = OnionExitOffer::new([OnionServiceName::https()], open_policy()?)?;
371        let both = OnionRole::Exit(exit.clone()).with_invoke(invoke.clone());
372        assert!(both.registers_relay());
373        assert_eq!(both.exit(), Some(&exit));
374        assert_eq!(both.invoke(), Some(&invoke));
375        Ok(())
376    }
377
378    /// An offer needs a service and an open policy.
379    #[test]
380    fn test_exit_offer_rejects_empty_services_and_closed_policy() -> Result<()> {
381        assert!(OnionExitOffer::new(Vec::new(), open_policy()?).is_err());
382        assert!(matches!(
383            OnionExitOffer::new(vec![OnionServiceName::https()], OnionExitPolicy::default()),
384            Err(Error::InvalidConfig(message)) if message.contains("allowed target")
385        ));
386        Ok(())
387    }
388
389    /// `try_map` is the traversal of `map`: it preserves the rung and fails only on the exit.
390    #[test]
391    fn test_try_map_traverses_the_exit_rung() {
392        let halve = |value: u8| value.is_multiple_of(2).then_some(value / 2).ok_or(value);
393
394        assert_eq!(
395            OnionRole::<u8, u8>::Exit(8).try_map(halve),
396            Ok(OnionRole::Exit(4))
397        );
398        assert_eq!(OnionRole::<u8, u8>::Exit(7).try_map(halve), Err(7));
399        assert_eq!(
400            OnionRole::<u8, u8>::Invoke(3).try_map(halve),
401            Ok(OnionRole::Invoke(3))
402        );
403        assert_eq!(
404            OnionRole::<u8, u8>::Relay.try_map(halve),
405            Ok(OnionRole::Relay)
406        );
407        assert_eq!(
408            OnionRole::<u8, u8>::Client.try_map(halve),
409            Ok(OnionRole::Client)
410        );
411    }
412
413    /// `map` preserves the rung, and every rung above `Client` registers `relay`.
414    #[test]
415    fn test_map_preserves_the_rung() {
416        let roles = [
417            OnionRole::<u8, u8>::Client,
418            OnionRole::Relay,
419            OnionRole::Invoke(5),
420            OnionRole::Exit(7),
421            OnionRole::Both { exit: 7, invoke: 5 },
422        ];
423
424        for role in roles {
425            let mapped = role.map(u16::from);
426            assert_eq!(mapped.registers_relay(), role.registers_relay());
427            assert_eq!(mapped.exit().copied(), role.exit().copied().map(u16::from));
428            assert_eq!(mapped.invoke(), role.invoke());
429        }
430        assert!(!OnionRole::<u8, u8>::Client.registers_relay());
431        assert!(OnionRole::<u8, u8>::Relay.registers_relay());
432    }
433}